1 /* 2 * Copyright 2008, Axel Dörfler, axeld@pinc-software.de. 3 * Distributed under the terms of the MIT License. 4 */ 5 6 7 #include <ctype.h> 8 #include <errno.h> 9 #include <fcntl.h> 10 #include <stdio.h> 11 #include <stdlib.h> 12 #include <string.h> 13 #include <sys/stat.h> 14 #include <unistd.h> 15 16 17 extern const char *__progname; 18 19 20 int 21 main(int argc, char **argv) 22 { 23 if (argc < 3) { 24 fprintf(stderr, "usage: %s <file> <size>\n", __progname); 25 return 1; 26 } 27 28 struct stat st; 29 if (stat(argv[1], &st) != 0) { 30 fprintf(stderr, "%s: cannot stat file \"%s\": %s\n", __progname, 31 argv[1], strerror(errno)); 32 return 1; 33 } 34 35 off_t newSize = strtoll(argv[2], NULL, 0); 36 37 printf("size %10Ld\n", st.st_size); 38 printf("wanted %10Ld\n", newSize); 39 printf("Do you really want to truncate the file [y/N]? "); 40 fflush(stdout); 41 42 char yes[10]; 43 if (fgets(yes, sizeof(yes), stdin) == NULL || tolower(yes[0]) != 'y') 44 return 0; 45 46 if (truncate(argv[1], newSize) != 0) { 47 fprintf(stderr, "%s: cannot truncate file \"%s\": %s\n", __progname, 48 argv[1], strerror(errno)); 49 return 1; 50 } 51 52 int fd = open(argv[1], O_RDONLY); 53 if (fd < 0) { 54 fprintf(stderr, "%s: could open the file read-only \"%s\": %s\n", 55 __progname, argv[1], strerror(errno)); 56 return 1; 57 } 58 if (ftruncate(fd, newSize) == 0 || errno != EINVAL) { 59 fprintf(stderr, "%s: could truncate a file opened read-only \"%s\": %s\n", 60 __progname, argv[1], strerror(errno)); 61 close(fd); 62 return 1; 63 } 64 close(fd); 65 66 return 0; 67 } 68