maint: sort: style adjustment to help clarify size determination
[coreutils.git] / src / truncate.c
blobe37ab38002ba39554fcd28757eeee2b54a0f4ed6
1 /* truncate -- truncate or extend the length of files.
2 Copyright (C) 2008-2012 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 #include <config.h> /* sets _FILE_OFFSET_BITS=64 etc. */
24 #include <stdio.h>
25 #include <getopt.h>
26 #include <sys/types.h>
28 #include "system.h"
29 #include "error.h"
30 #include "quote.h"
31 #include "stat-size.h"
32 #include "xstrtol.h"
34 /* The official name of this program (e.g., no 'g' prefix). */
35 #define PROGRAM_NAME "truncate"
37 #define AUTHORS proper_name_utf8 ("Padraig Brady", "P\303\241draig Brady")
39 /* (-c) If true, don't create if not already there */
40 static bool no_create;
42 /* (-o) If true, --size refers to blocks not bytes */
43 static bool block_mode;
45 /* (-r) Reference file to use size from */
46 static char const *ref_file;
48 static struct option const longopts[] =
50 {"no-create", no_argument, NULL, 'c'},
51 {"io-blocks", no_argument, NULL, 'o'},
52 {"reference", required_argument, NULL, 'r'},
53 {"size", required_argument, NULL, 's'},
54 {GETOPT_HELP_OPTION_DECL},
55 {GETOPT_VERSION_OPTION_DECL},
56 {NULL, 0, NULL, 0}
59 typedef enum
60 { rm_abs = 0, rm_rel, rm_min, rm_max, rm_rdn, rm_rup } rel_mode_t;
62 /* Set size to the value of STR, interpreted as a decimal integer,
63 optionally multiplied by various values.
64 Return -1 on error, 0 on success.
66 This supports dd BLOCK size suffixes + lowercase g,t,m for bsd compat
67 Note we don't support dd's b=512, c=1, w=2 or 21x512MiB formats. */
68 static int
69 parse_len (char const *str, off_t *size)
71 enum strtol_error e;
72 intmax_t tmp_size;
73 e = xstrtoimax (str, NULL, 10, &tmp_size, "EgGkKmMPtTYZ0");
74 if (e == LONGINT_OK
75 && !(OFF_T_MIN <= tmp_size && tmp_size <= OFF_T_MAX))
76 e = LONGINT_OVERFLOW;
78 if (e == LONGINT_OK)
80 errno = 0;
81 *size = tmp_size;
82 return 0;
85 errno = (e == LONGINT_OVERFLOW ? EOVERFLOW : 0);
86 return -1;
89 void
90 usage (int status)
92 if (status != EXIT_SUCCESS)
93 emit_try_help ();
94 else
96 printf (_("Usage: %s OPTION... FILE...\n"), program_name);
97 fputs (_("\
98 Shrink or extend the size of each FILE to the specified size\n\
99 \n\
100 A FILE argument that does not exist is created.\n\
102 If a FILE is larger than the specified size, the extra data is lost.\n\
103 If a FILE is shorter, it is extended and the extended part (hole)\n\
104 reads as zero bytes.\n\
106 "), stdout);
107 fputs (_("\
108 Mandatory arguments to long options are mandatory for short options too.\n\
109 "), stdout);
110 fputs (_("\
111 -c, --no-create do not create any files\n\
112 "), stdout);
113 fputs (_("\
114 -o, --io-blocks treat SIZE as number of IO blocks instead of bytes\n\
115 "), stdout);
116 fputs (_("\
117 -r, --reference=RFILE base size on RFILE\n\
118 -s, --size=SIZE set or adjust the file size by SIZE\n"), stdout);
119 fputs (HELP_OPTION_DESCRIPTION, stdout);
120 fputs (VERSION_OPTION_DESCRIPTION, stdout);
121 emit_size_note ();
122 fputs (_("\n\
123 SIZE may also be prefixed by one of the following modifying characters:\n\
124 '+' extend by, '-' reduce by, '<' at most, '>' at least,\n\
125 '/' round down to multiple of, '%' round up to multiple of.\n"), stdout);
126 emit_ancillary_info ();
128 exit (status);
131 /* return true on success, false on error. */
132 static bool
133 do_ftruncate (int fd, char const *fname, off_t ssize, off_t rsize,
134 rel_mode_t rel_mode)
136 struct stat sb;
137 off_t nsize;
139 if ((block_mode || (rel_mode && rsize < 0)) && fstat (fd, &sb) != 0)
141 error (0, errno, _("cannot fstat %s"), quote (fname));
142 return false;
144 if (block_mode)
146 off_t const blksize = ST_BLKSIZE (sb);
147 if (ssize < OFF_T_MIN / blksize || ssize > OFF_T_MAX / blksize)
149 error (0, 0,
150 _("overflow in %" PRIdMAX
151 " * %" PRIdMAX " byte blocks for file %s"),
152 (intmax_t) ssize, (intmax_t) blksize,
153 quote (fname));
154 return false;
156 ssize *= blksize;
158 if (rel_mode)
160 uintmax_t fsize;
162 if (0 <= rsize)
163 fsize = rsize;
164 else
166 off_t file_size;
167 if (usable_st_size (&sb))
169 file_size = sb.st_size;
170 if (file_size < 0)
172 /* Sanity check. Overflow is the only reason I can think
173 this would ever go negative. */
174 error (0, 0, _("%s has unusable, apparently negative size"),
175 quote (fname));
176 return false;
179 else
181 file_size = lseek (fd, 0, SEEK_END);
182 if (file_size < 0)
184 error (0, errno, _("cannot get the size of %s"),
185 quote (fname));
186 return false;
189 fsize = file_size;
192 if (rel_mode == rm_min)
193 nsize = MAX (fsize, (uintmax_t) ssize);
194 else if (rel_mode == rm_max)
195 nsize = MIN (fsize, (uintmax_t) ssize);
196 else if (rel_mode == rm_rdn)
197 /* 0..ssize-1 -> 0 */
198 nsize = (fsize / ssize) * ssize;
199 else if (rel_mode == rm_rup)
200 /* 1..ssize -> ssize */
202 /* Here ssize>=1 && fsize>=0 */
203 uintmax_t const overflow = ((fsize + ssize - 1) / ssize) * ssize;
204 if (overflow > OFF_T_MAX)
206 error (0, 0, _("overflow rounding up size of file %s"),
207 quote (fname));
208 return false;
210 nsize = overflow;
212 else
214 if (ssize > OFF_T_MAX - (off_t)fsize)
216 error (0, 0, _("overflow extending size of file %s"),
217 quote (fname));
218 return false;
220 nsize = fsize + ssize;
223 else
224 nsize = ssize;
225 if (nsize < 0)
226 nsize = 0;
228 if (ftruncate (fd, nsize) == -1) /* note updates mtime & ctime */
230 error (0, errno,
231 _("failed to truncate %s at %" PRIdMAX " bytes"), quote (fname),
232 (intmax_t) nsize);
233 return false;
236 return true;
240 main (int argc, char **argv)
242 bool got_size = false;
243 bool errors = false;
244 off_t size IF_LINT ( = 0);
245 off_t rsize = -1;
246 rel_mode_t rel_mode = rm_abs;
247 mode_t omode;
248 int c, fd = -1, oflags;
249 char const *fname;
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)
261 switch (c)
263 case 'c':
264 no_create = true;
265 break;
267 case 'o':
268 block_mode = true;
269 break;
271 case 'r':
272 ref_file = optarg;
273 break;
275 case 's':
276 /* skip any whitespace */
277 while (isspace (to_uchar (*optarg)))
278 optarg++;
279 switch (*optarg)
281 case '<':
282 rel_mode = rm_max;
283 optarg++;
284 break;
285 case '>':
286 rel_mode = rm_min;
287 optarg++;
288 break;
289 case '/':
290 rel_mode = rm_rdn;
291 optarg++;
292 break;
293 case '%':
294 rel_mode = rm_rup;
295 optarg++;
296 break;
298 /* skip any whitespace */
299 while (isspace (to_uchar (*optarg)))
300 optarg++;
301 if (*optarg == '+' || *optarg == '-')
303 if (rel_mode)
305 error (0, 0, _("multiple relative modifiers specified"));
306 /* Note other combinations are flagged as invalid numbers */
307 usage (EXIT_FAILURE);
309 rel_mode = rm_rel;
311 if (parse_len (optarg, &size) == -1)
312 error (EXIT_FAILURE, errno, _("invalid number %s"),
313 quote (optarg));
314 /* Rounding to multiple of 0 is nonsensical */
315 if ((rel_mode == rm_rup || rel_mode == rm_rdn) && size == 0)
316 error (EXIT_FAILURE, 0, _("division by zero"));
317 got_size = true;
318 break;
320 case_GETOPT_HELP_CHAR;
322 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
324 default:
325 usage (EXIT_FAILURE);
329 argv += optind;
330 argc -= optind;
332 /* must specify either size or reference file */
333 if (!ref_file && !got_size)
335 error (0, 0, _("you must specify either %s or %s"),
336 quote_n (0, "--size"), quote_n (1, "--reference"));
337 usage (EXIT_FAILURE);
339 /* must specify a relative size with a reference file */
340 if (ref_file && got_size && !rel_mode)
342 error (0, 0, _("you must specify a relative %s with %s"),
343 quote_n (0, "--size"), quote_n (1, "--reference"));
344 usage (EXIT_FAILURE);
346 /* block_mode without size is not valid */
347 if (block_mode && !got_size)
349 error (0, 0, _("%s was specified but %s was not"),
350 quote_n (0, "--io-blocks"), quote_n (1, "--size"));
351 usage (EXIT_FAILURE);
353 /* must specify at least 1 file */
354 if (argc < 1)
356 error (0, 0, _("missing file operand"));
357 usage (EXIT_FAILURE);
360 if (ref_file)
362 struct stat sb;
363 off_t file_size = -1;
364 if (stat (ref_file, &sb) != 0)
365 error (EXIT_FAILURE, errno, _("cannot stat %s"), quote (ref_file));
366 if (usable_st_size (&sb))
367 file_size = sb.st_size;
368 else
370 int ref_fd = open (ref_file, O_RDONLY);
371 if (0 <= ref_fd)
373 off_t file_end = lseek (ref_fd, 0, SEEK_END);
374 if (0 <= file_end && close (ref_fd) == 0)
375 file_size = file_end;
378 if (file_size < 0)
379 error (EXIT_FAILURE, errno, _("cannot get the size of %s"),
380 quote (ref_file));
381 if (!got_size)
382 size = file_size;
383 else
384 rsize = file_size;
387 oflags = O_WRONLY | (no_create ? 0 : O_CREAT) | O_NONBLOCK;
388 omode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
390 while ((fname = *argv++) != NULL)
392 if ((fd = open (fname, oflags, omode)) == -1)
394 /* 'truncate -s0 -c no-such-file' shouldn't gen error
395 'truncate -s0 no-such-dir/file' should gen ENOENT error
396 'truncate -s0 no-such-dir/' should gen EISDIR error
397 'truncate -s0 .' should gen EISDIR error */
398 if (!(no_create && errno == ENOENT))
400 error (0, errno, _("cannot open %s for writing"),
401 quote (fname));
402 errors = true;
404 continue;
408 if (fd != -1)
410 errors |= !do_ftruncate (fd, fname, size, rsize, rel_mode);
411 if (close (fd) != 0)
413 error (0, errno, _("closing %s"), quote (fname));
414 errors = true;
419 return errors ? EXIT_FAILURE : EXIT_SUCCESS;