k9core

Coreutils for *nix operating systems [fork]
git clone git://bvnf.space/k9core.git
Log | Files | Refs | LICENSE

shred.c (1151B)


      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int
fill_with_zeroes(const char *filename)
{
	int fd = open(filename, O_WRONLY);
	if(fd == -1) {
		fprintf(stderr, "shred: %s: %s\n", filename, strerror(errno));
		return 1;
	}
	struct stat stat_struct; /* What name should i use? */
	if(stat(filename, &stat_struct) == -1) {
		fprintf(stderr, "shred: %s: %s\n", filename, strerror(errno));
		return 1;
	}
	long int bytes_to_write = stat_struct.st_size;

	for(int i = 0; i < bytes_to_write; i++)
		if(write(fd, "\0", 1) == -1) {
			fprintf(stderr, "shred: %s: %s\n", filename, strerror(errno));
			return 1;
		}
	if(fsync(fd) == -1) {
		fprintf(stderr, "shred: %s: %s\n", filename, strerror(errno));
		return 1;
	}
	close(fd);
	return 0;
}

int
main(int argc, char *argv[])
{
	int c = getopt(argc, argv, "u"); /* TODO: add -f */

	if(fill_with_zeroes(argv[optind]) != 0) {
		return 1;
	}
	if(c == 'u')
		if(remove(argv[optind]) == -1) {
			fprintf(
				stderr, "shred: %s: %s\n", argv[optind], strerror(errno));
			return 1;
		}
	return 0;
}