Mega Code Archive

 
Categories / C / Development
 

Create 1 MB test garbage file

#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <getopt.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #define PACKAGE "garfile" #define MB 1024 * 1024 void print_help(int exval); int main(int argc, char *argv[]) { int opt = 0; char *mptr; int fd = -1; int megabyte = MB; if(argc == 1) print_help(1); /* option parser */ while((opt = getopt(argc, argv, "h")) != -1) { switch(opt) { case 'h': print_help(0); case '?': /* no such option */ fprintf(stderr, "%s: Error - No such option: `%c'\n\n", PACKAGE, optopt); print_help(1); } } if((argc - optind) == 0) print_help(1); for(; optind < argc; optind++) { if((mptr = malloc(megabyte)) == NULL) { fprintf(stderr, "%s: Error - malloc(%d)\n", PACKAGE, megabyte); return 1; } memset(mptr, '\0', sizeof(mptr)); if((fd = open(argv[optind], O_RDWR|O_CREAT|O_TRUNC, 0666)) == -1) { fprintf(stderr, "%s: Error - open(%s)\n", PACKAGE, argv[optind]); return 1; } write(fd, mptr, megabyte); close(fd); } free(mptr); return 0; } /* status epilepticus, print help and exit with exval */ void print_help(int exval) { printf("%s create a test file filled with `\\0' of 1 Megabyte in size\n", PACKAGE); printf("Usage: %s [-h] FILE1 FILE2 FILE3...\n\n", PACKAGE); printf(" -h print this help and exit\n\n"); exit(exval); }