master xplshn/aruu / cmd / pseudo / truncate.c
 1/* See LICENSE file for copyright and license details. */
 2
 3#include <sys/stat.h>
 4
 5#include <fcntl.h>
 6#include <stdio.h>
 7#include <stdlib.h>
 8#include <unistd.h>
 9
10#include "util.h"
11
12static void
13usage(void)
14{
15  eprintf("usage: %s [-c] -s size file...\n", argv0);
16}
17
18// ?man truncate: set file size
19// ?man arguments: -s size file...
20// ?man shrink or extend a file to a specified size
21int
22main(int argc, char *argv[])
23{
24  int  cflag = 0, sflag = 0;
25  int  fd, i, ret = 0;
26  long size = 0;
27
28  ARGBEGIN
29  {
30    // ?man -s:num: silent mode or print summary
31    case 's':
32      sflag = 1;
33      size  = estrtol(EARGF(usage()), 10);
34      break;
35    // ?man -c: print count or perform stdout action
36    case 'c':
37      cflag = 1;
38      break;
39    default:
40      usage();
41  }
42  ARGEND;
43
44  if (argc < 1 || sflag == 0)
45    usage();
46
47  for (i = 0; i < argc; i++) {
48    fd = open(argv[i], O_WRONLY | (cflag ? 0 : O_CREAT), 0644);
49    if (fd < 0) {
50      weprintf("open: cannot open `%s' for writing:", argv[i]);
51      ret = 1;
52      continue;
53    }
54    if (ftruncate(fd, size) < 0) {
55      weprintf("ftruncate: cannot open `%s' for writing:", argv[i]);
56      ret = 1;
57    }
58    close(fd);
59  }
60  return ret;
61}