2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2000 Sheldon Hearn <sheldonh@FreeBSD.org>.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 static const char rcsid[] =
47 static void usage(void);
50 static int do_relative;
55 main(int argc, char **argv)
59 off_t oflow, rsize, sz, tsize;
61 int ch, error, fd, oflags;
65 rsize = tsize = sz = 0;
68 while ((ch = getopt(argc, argv, "cr:s:")) != -1)
78 do_relative = *optarg == '+' || *optarg == '-';
79 if (expand_number(do_relative ? optarg + 1 : optarg,
80 &usz) == -1 || (off_t)usz < 0)
82 "invalid size argument `%s'", optarg);
84 sz = (*optarg == '-') ? -(off_t)usz : (off_t)usz;
96 * Exactly one of do_refer or got_size must be specified. Since
97 * do_relative implies got_size, do_relative and do_refer are
98 * also mutually exclusive. See usage() for allowed invocations.
100 if (do_refer + got_size != 1 || argc < 1)
103 if (stat(rname, &sb) == -1)
104 err(EXIT_FAILURE, "%s", rname);
106 } else if (do_relative)
114 oflags = O_WRONLY | O_CREAT;
115 omode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
117 while ((fname = *argv++) != NULL) {
120 if ((fd = open(fname, oflags, omode)) == -1) {
121 if (errno != ENOENT) {
128 if (fstat(fd, &sb) == -1) {
133 oflow = sb.st_size + rsize;
134 if (oflow < (sb.st_size + rsize)) {
145 if (ftruncate(fd, tsize) == -1) {
154 return error ? EXIT_FAILURE : EXIT_SUCCESS;
160 fprintf(stderr, "%s\n%s\n",
161 "usage: truncate [-c] -s [+|-]size[K|k|M|m|G|g|T|t] file ...",
162 " truncate [-c] -r rfile file ...");