#define _ISOC99_SOURCE 1 #define _BSD_SOURCE 1 #include #include #include #include #include #include #include #include #define MAX_INT_SIZE_HALF(the_int) \ ((the_int)1 << ((CHAR_BIT) * \ (sizeof(the_int)) - 1 - ((the_int)-1 < 1?1:0))) #define MAX_INT_SIZE(the_int) \ ((MAX_INT_SIZE_HALF(the_int) - 1) + MAX_INT_SIZE_HALF(the_int)) int main(int argc, char *argv[]) { intmax_t size; off_t the_size; char *file; int fd; if (argc != 3) { fprintf(stderr, "Usage: %s \n", argv[0]); exit(EXIT_FAILURE); } file = argv[1]; if (sscanf(argv[2], "%jd", &size) != 1 || size < 0 || size > (intmax_t)MAX_INT_SIZE(off_t)) { if (size < 0) fprintf(stderr, "Size has to be a positive integer.\n"); else fprintf(stderr, "Size is too big. Maximum is: %jd.\n", (intmax_t)MAX_INT_SIZE(off_t)); exit(EXIT_FAILURE); } the_size = (off_t) size; fd = open(file, O_RDWR | O_CREAT | O_EXCL, DEFFILEMODE); if (fd < 0) { perror("Error opening file"); exit(EXIT_FAILURE); } if (ftruncate(fd, the_size) < 0) { perror("Error truncating file"); close(fd); unlink(file); exit(EXIT_FAILURE); } close(fd); exit(EXIT_SUCCESS); }