filefiller/filefiller.c

159 lines
3.6 KiB
C

/* standard stuff */
#include <stdio.h>
#include <stdlib.h>
/* malloc */
#include <malloc.h>
/* memset */
#include <string.h>
/* error handling */
#include <errno.h>
/* rate */
#include <time.h>
/* explicitly compile with -D_OFFSET_FILE_BITS=64 if it fails at 2G */
#define _FILE_OFFSET_BITS 64
#define TUI
#define BARLEN 80
#define NAME "filefiller"
#define VERSION "0.1"
#define ME "cancer"
/* #define DEBUG */
#define BLOCKSIZE (unsigned long long)4096
#define REFRESHINTERVAL 1024
#define FILLCHAR 0x00
void usage(char *binname) {
printf("%s v%s\n\n Usage:\n %s filename blocks\n\n This executable uses:\n BLOCKSIZE = %llu\n REFRESHINTERVAL = %d\n FILLCHAR = 0x%X\n\n~%s\n", NAME, VERSION, binname, BLOCKSIZE, REFRESHINTERVAL, FILLCHAR, ME);
exit(0);
}
int main(int argc, char **argv) {
if(argc < 3) usage(argv[0]);
FILE *fd;
fd = fopen(argv[1], "r");
if(fd != NULL) {
#ifdef DEBUG
printf("File exists, removing.");
#endif
fclose(fd);
remove(argv[1]);
}
fd = fopen(argv[1], "wb");
size_t x = 0;
char *b = malloc(sizeof(char)*BLOCKSIZE);
#ifdef DEBUG
printf("Allocated %llu bytes.\n", BLOCKSIZE);
#endif
unsigned long long c = atoll(argv[2]);
memset(b, FILLCHAR, BLOCKSIZE);
#ifdef DEBUG
printf("Zeroed %llu bytes.\n", BLOCKSIZE);
#endif
#ifdef TUI
puts("FILENAME PERCENT BLOCKS_DONE BLOCKS_LEFT BLOCKS_TOT FILESIZE");
#endif
time_t starttime = time(0);
time_t endtime = time(0);
unsigned long long blocksintime = 0;
unsigned long long totalblocks = 0;
for(unsigned long long i = 1; i <= c; i++) {
if((x = fwrite(b, sizeof(char), BLOCKSIZE, fd)) < BLOCKSIZE) {
#ifdef DEBUG
if(ferror(fd)) {
printf("ferror\n");
printf("%d %s \n", errno, strerror(errno));
}
else if(feof(fd)) {
printf("\reof\n");
}
else {
printf("\r%d %s \n", errno, strerror(errno));
}
printf("Wrote %llu bytes instead of %llu.\n", (unsigned long long)x, BLOCKSIZE);
#endif
puts("\n");
fclose(fd);
remove(argv[1]);
return EXIT_FAILURE;
}
blocksintime++;
endtime = time(0);
if(endtime > starttime) {
totalblocks = blocksintime;
blocksintime = 0;
starttime = endtime;
}
if(i % REFRESHINTERVAL == 0 || i == c) {
#ifdef TUI
printf("\r%-8s %-7.2lf %-11llu %-11llu %-11llu", argv[1], ((double)i/(double)c*100), i, c-i, c);
unsigned long long X = i*BLOCKSIZE;
char *sizes = " KMGTPEZY";
while(X >= 1024) {
X >>= 10;
sizes++;
}
printf("%llu%-4c ", X, *sizes);
X = totalblocks*BLOCKSIZE;
sizes = " KMGTPEZY";
while(X >= 1024) {
X >>= 10;
sizes++;
}
printf("%lldblk/s %lld%cbits/s\033[K\n[\033[7m\033[2G", totalblocks, X*8, *sizes);
for(unsigned int j = 2; j < (unsigned int)((double)i/(double)c*BARLEN); j++) {
printf(" ");
}
printf("\033[0m\033[%dG]\033[1A\r", BARLEN);
#endif
}
}
puts("\n");
#if defined(DEBUG) || !defined(TUI)
printf("Wrote %llu blocks of %llu (=%llu bytes) to file %s.\n", c, BLOCKSIZE, c*BLOCKSIZE, argv[1]);
#endif
free(b);
fclose(fd);
}