master xplshn/aruu / cmd / pseudo / fallocate.c
 1/* See LICENSE file for copyright and license details. */
 2
 3#include <sys/stat.h>
 4
 5#include <fcntl.h>
 6#include <limits.h>
 7#include <stdint.h>
 8#include <stdio.h>
 9#include <stdlib.h>
10#include <unistd.h>
11
12#include "util.h"
13
14static void
15usage(void)
16{
17  eprintf("usage: %s [-o num] -l num file ...\n", argv0);
18}
19
20// ?man fallocate: preallocate file space
21// ?man arguments: -l num file ...
22// ?man preallocate or deallocate space to a file
23int
24main(int argc, char *argv[])
25{
26  int   fd, ret = 0;
27  off_t size = 0, offset = 0;
28
29  ARGBEGIN
30  {
31    // ?man -l:num: list in long format
32    case 'l':
33      size = estrtonum(
34          EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)
35      );
36      break;
37    // ?man -o:num: specify output file
38    case 'o':
39      offset = estrtonum(
40          EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)
41      );
42      break;
43    default:
44      usage();
45  }
46  ARGEND;
47
48  if (!argc || !size)
49    usage();
50
51  for (; *argv; argc--, argv++) {
52    if ((fd = open(*argv, O_RDWR | O_CREAT, 0644)) < 0) {
53      weprintf("open %s:", *argv);
54      ret = 1;
55    } else if (posix_fallocate(fd, offset, size) < 0) {
56      weprintf("posix_fallocate %s:", *argv);
57      ret = 1;
58    }
59
60    if (fd >= 0 && close(fd) < 0) {
61      weprintf("close %s:", *argv);
62      ret = 1;
63    }
64  }
65
66  return ret;
67}