/* * nullfile.c * * 2000-02-06 Fredrik Roubert * 2003-09-29 Fredrik Roubert * 2004-06-11 Fredrik Roubert * */ #if defined(__LONG_LONG_MAX__) || defined(sun) # define _FILE_OFFSET_BITS 64 #endif #include #include #include #include #include #include #include static const unsigned char zero = 0; static const char optstr[] = "hs:m:"; static void usage(FILE *stream, const char *name) { fprintf(stream, "Usage: %s [-s size] [-m mode] [file ...]\n", name); } int main(int argc, char *argv[]) { #if _FILE_OFFSET_BITS == 64 unsigned long long size; #else unsigned long size; #endif unsigned long mode; const char *name; int fd, c, setmode; size = 0; mode = 0666; setmode = 0; for (; (c = getopt(argc, argv, optstr)) != EOF;) switch (c) { case 'h': usage(stdout, argv[0]); return EXIT_SUCCESS; case 's': errno = 0; #if _FILE_OFFSET_BITS == 64 size = strtoull(optarg, NULL, 0); #else size = strtoul(optarg, NULL, 0); #endif if (errno != 0) { perror(optarg); return EXIT_FAILURE; } break; case 'm': errno = 0; mode = strtoul(optarg, NULL, 8); if (errno != 0) { perror(optarg); return EXIT_FAILURE; } setmode = 1; break; case '?': usage(stderr, argv[0]); return EXIT_FAILURE; default: fprintf(stderr, "%s: Error parsing command line, " "getopt() returned 0x%02x\n", argv[0], c); return EXIT_FAILURE; } if (mode > 07777) { fprintf(stderr, "%s: %lo: Bad file mode\n", argv[0], mode); return EXIT_FAILURE; } if (optind == argc) { usage(stderr, argv[0]); return EXIT_FAILURE; } for (; optind < argc; optind ++) { name = argv[optind]; if ((fd = open(name, O_WRONLY | O_CREAT | O_TRUNC, mode)) == -1) { perror(name); return EXIT_FAILURE; } if (setmode && fchmod(fd, mode) == -1) { perror(name); return EXIT_FAILURE; } if (size > 0) { if (size > 1) { if (lseek(fd, size - 1, SEEK_SET) == -1) { perror(name); return EXIT_FAILURE; } } if (write(fd, &zero, 1) == -1) { perror(name); return EXIT_FAILURE; } } if (close(fd) == -1) { perror(name); return EXIT_FAILURE; } } return EXIT_SUCCESS; }