1 /* truncate -- truncate or extend the length of files.
2 Copyright (C) 2008 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Pádraig Brady
19 This is backwards compatible with the FreeBSD utility, but is more
20 flexible wrt the size specifications and the use of long options,
21 to better fit the "GNU" environment.
23 Note if !defined(HAVE_FTRUNCATE) then the --skip-ftruncate configure flag
24 was specified or we're in a mingw environment. In these cases gnulib
25 emulation will be used and GNULIB_FTRUNCATE is defined. Note if emulation
26 can't even be provided ftruncate() will return EIO. */
28 #include <config.h> /* sets _FILE_OFFSET_BITS=64 etc. */
31 #include <sys/types.h>
39 /* The official name of this program (e.g., no `g' prefix). */
40 #define PROGRAM_NAME "truncate"
42 #define AUTHORS proper_name_utf8 ("Padraig Brady", "P\303\241draig Brady")
44 /* (-c) If true, don't create if not already there */
45 static bool no_create;
47 /* (-o) If true, --size refers to blocks not bytes */
48 static bool block_mode;
50 /* (-r) Reference file to use size from */
51 static char const *ref_file;
53 static struct option const longopts[] = {
54 {"no-create", no_argument, NULL, 'c'},
55 {"io-blocks", no_argument, NULL, 'o'},
56 {"reference", required_argument, NULL, 'r'},
57 {"size", required_argument, NULL, 's'},
58 {GETOPT_HELP_OPTION_DECL},
59 {GETOPT_VERSION_OPTION_DECL},
64 { rm_abs = 0, rm_rel, rm_min, rm_max, rm_rdn, rm_rup } rel_mode_t;
66 /* Set size to the value of STR, interpreted as a decimal integer,
67 optionally multiplied by various values.
68 Return -1 on error, 0 on success.
70 This supports dd BLOCK size suffixes + lowercase g,t,m for bsd compat
71 Note we don't support dd's b=512, c=1, w=2 or 21x512MiB formats. */
73 parse_len (char const *str, off_t *size)
76 /* OFF_T_MAX = INTMAX_MAX */
77 e = xstrtoimax (str, NULL, 10, size, "EgGkKmMPtTYZ0");
78 errno = (e == LONGINT_OVERFLOW) ? EOVERFLOW : 0;
79 return (e == LONGINT_OK) ? 0 : -1;
85 if (status != EXIT_SUCCESS)
86 fprintf (stderr, _("Try `%s --help' for more information.\n"),
90 printf (_("Usage: %s OPTION... FILE...\n"), program_name);
92 Shrink or extend the size of each FILE to the specified size\n\
94 A FILE argument that does not exist is created.\n\
96 If a FILE is larger than the specified size, the extra data is lost.\n\
97 If a FILE is shorter, it is extended and the extended part (hole)\n\
98 reads as zero bytes.\n\
102 Mandatory arguments to long options are mandatory for short options too.\n\
105 -c, --no-create do not create any files\n\
108 -o, --io-blocks Treat SIZE as number of IO blocks instead of bytes\n\
111 -r, --reference=FILE use this FILE's size\n\
112 -s, --size=SIZE use this SIZE\n"), stdout);
113 fputs (HELP_OPTION_DESCRIPTION, stdout);
114 fputs (VERSION_OPTION_DESCRIPTION, stdout);
116 SIZE is a number which may be followed by one of the following suffixes:\n\
117 KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
120 SIZE may also be prefixed by one of the following modifying characters:\n\
121 `+' extend by, `-' reduce by, `<' at most, `>' at least,\n\
122 `/' round down to multiple of, `%' round up to multiple of.\n"), stdout);
125 Note that the -r and -s options are mutually exclusive.\n\
127 emit_bug_reporting_address ();
132 /* return 1 on error, 0 on success */
134 do_ftruncate (int fd, char const *fname, off_t ssize, rel_mode_t rel_mode)
139 if ((block_mode || rel_mode) && fstat (fd, &sb) != 0)
141 error (0, errno, _("cannot fstat %s"), quote (fname));
146 size_t const blksize = ST_BLKSIZE (sb);
147 if (ssize < OFF_T_MIN / blksize || ssize > OFF_T_MAX / blksize)
150 _("overflow in %" PRIdMAX
151 " * %zu byte blocks for file %s"), ssize, blksize,
159 uintmax_t const fsize = sb.st_size;
163 /* Complain only for a regular file, a directory,
164 or a shared memory object, as POSIX 1003.1-2004 specifies
165 ftruncate's behavior only for these file types. */
166 if (S_ISREG (sb.st_mode) || S_ISDIR (sb.st_mode)
167 || S_TYPEISSHM (&sb))
169 /* overflow is the only reason I can think
170 this would ever go negative for the above types */
171 error (0, 0, _("%s has unusable, apparently negative size"),
178 if (rel_mode == rm_min)
179 nsize = MAX (fsize, ssize);
180 else if (rel_mode == rm_max)
181 nsize = MIN (fsize, ssize);
182 else if (rel_mode == rm_rdn)
183 /* 0..ssize-1 -> 0 */
184 nsize = (fsize / ssize) * ssize;
185 else if (rel_mode == rm_rup)
186 /* 1..ssize -> ssize */
188 /* Here ssize>=1 && fsize>=0 */
189 uintmax_t const overflow = ((fsize + ssize - 1) / ssize) * ssize;
190 if (overflow > OFF_T_MAX)
192 error (0, 0, _("overflow rounding up size of file %s"),
200 if (ssize > OFF_T_MAX - (off_t)fsize)
202 error (0, 0, _("overflow extending size of file %s"),
206 nsize = fsize + ssize;
214 if (ftruncate (fd, nsize) == -1) /* note updates mtime & ctime */
216 /* Complain only when ftruncate fails on a regular file, a
217 directory, or a shared memory object, as POSIX 1003.1-2004
218 specifies ftruncate's behavior only for these file types.
219 For example, do not complain when Linux 2.4 ftruncate
220 fails on /dev/fd0. */
221 int const ftruncate_errno = errno;
222 if (fstat (fd, &sb) != 0)
224 error (0, errno, _("cannot fstat %s"), quote (fname));
227 else if (S_ISREG (sb.st_mode) || S_ISDIR (sb.st_mode)
228 || S_TYPEISSHM (&sb))
230 error (0, ftruncate_errno,
231 _("truncating %s at %" PRIdMAX " bytes"), quote (fname),
242 main (int argc, char **argv)
244 bool got_size = false;
246 rel_mode_t rel_mode = rm_abs;
248 int c, errors = 0, fd = -1, oflags;
251 initialize_main (&argc, &argv);
252 set_program_name (argv[0]);
253 setlocale (LC_ALL, "");
254 bindtextdomain (PACKAGE, LOCALEDIR);
255 textdomain (PACKAGE);
257 atexit (close_stdout);
259 while ((c = getopt_long (argc, argv, "cor:s:", longopts, NULL)) != -1)
295 if (*optarg == '+' || *optarg == '-')
299 error (0, 0, _("multiple relative modifiers specified"));
300 /* Note other combinations are flagged as invalid numbers */
301 usage (EXIT_FAILURE);
305 if (parse_len (optarg, &size) == -1)
306 error (EXIT_FAILURE, errno, _("invalid number %s"),
308 /* Rounding to multiple of 0 is nonsensical */
309 if ((rel_mode == rm_rup || rel_mode == rm_rdn) && size == 0)
310 error (EXIT_FAILURE, 0, _("division by zero"));
314 case_GETOPT_HELP_CHAR;
316 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
319 usage (EXIT_FAILURE);
326 /* must specify either size or reference file */
327 if ((ref_file && got_size) || (!ref_file && !got_size))
329 error (0, 0, _("you must specify one of %s or %s"),
330 quote_n (0, "--size"), quote_n (1, "--reference"));
331 usage (EXIT_FAILURE);
333 /* block_mode without size is not valid */
334 if (block_mode && !got_size)
336 error (0, 0, _("%s was specified but %s was not"),
337 quote_n (0, "--io-blocks"), quote_n (1, "--size"));
338 usage (EXIT_FAILURE);
340 /* must specify at least 1 file */
343 error (0, 0, _("missing file operand"));
344 usage (EXIT_FAILURE);
350 if (stat (ref_file, &sb) != 0)
351 error (EXIT_FAILURE, errno, _("cannot stat %s"), quote (ref_file));
355 oflags = O_WRONLY | (no_create ? 0 : O_CREAT) | O_NONBLOCK;
356 omode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
358 while ((fname = *argv++) != NULL)
360 if ((fd = open (fname, oflags, omode)) == -1)
362 /* `truncate -s0 -c no-such-file` shouldn't gen error
363 `truncate -s0 no-such-dir/file` should gen ENOENT error
364 `truncate -s0 no-such-dir/` should gen EISDIR error
365 `truncate -s0 .` should gen EISDIR error */
366 if (!(no_create && errno == ENOENT))
368 int const open_errno = errno;
370 if (stat (fname, &sb) == 0)
372 /* Complain only for a regular file, a directory,
373 or a shared memory object, as POSIX 1003.1-2004 specifies
374 ftruncate's behavior only for these file types. */
375 if (!S_ISREG (sb.st_mode) && !S_ISDIR (sb.st_mode)
376 && !S_TYPEISSHM (&sb))
379 error (0, open_errno, _("cannot open %s for writing"),
389 errors += do_ftruncate (fd, fname, size, rel_mode);
392 error (0, errno, _("closing %s"), quote (fname));
398 return errors ? EXIT_FAILURE : EXIT_SUCCESS;
403 * indent-tabs-mode: nil