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