1 /* trunc.c: Set the size of an existing file, or create a file of a
4 * Copyright (C) 2008 Micah J. Cowan
6 * Copying and distribution of this file, with or without modification,
7 * are permitted in any medium without royalty provided the copyright
8 * notice and this notice are preserved. */
17 #define PROGRAM_NAME "trunc"
23 PROGRAM_NAME " [-c] file sz\n\
25 Set the filesize of FILE to SIZE.\n\
27 -c: create FILE if it doesn't exist.\n\
29 Multiplier suffixes for SIZE (case-insensitive):\n\
31 m: SIZE * 1024 * 1024\n", f);
35 get_size (const char str[])
42 val = strtoul(str, &end, 10);
45 fputs (PROGRAM_NAME ": size is not a number.\n", stderr);
49 else if (errno == ERANGE
50 || (unsigned long)(off_t)val != val)
52 fputs (PROGRAM_NAME ": size is out of range.\n", stderr);
56 suffix = tolower ((unsigned char) end[0]);
61 else if (suffix == 'm')
70 main (int argc, char *argv[])
80 while ((option = getopt (argc, argv, "c")) != -1)
87 fprintf (stderr, PROGRAM_NAME ": Unrecognized option `%c'.\n\n",
92 /* We shouldn't reach here. */
97 if (argv[optind] == NULL
98 || argv[optind+1] == NULL
99 || argv[optind+2] != NULL)
105 fname = argv[optind];
106 szstr = argv[optind+1];
108 sz = get_size(szstr);
111 mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
112 fd = open(fname, O_WRONLY | O_CREAT, mode);
116 fd = open(fname, O_WRONLY);
121 perror (PROGRAM_NAME ": open");
125 if (ftruncate(fd, sz) == -1)
127 perror (PROGRAM_NAME ": truncate");
133 perror (PROGRAM_NAME ": close");