aboutsummaryrefslogtreecommitdiff
path: root/toys/other/truncate.c
blob: dccd3215fb7a396a8ea70336d4001b1daf98aef3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/* vi: set sw=4 ts=4:
 *
 * truncate.c - set file length, extending sparsely if necessary
 *
 * Copyright 2011 Rob Landley <rob@landley.net>
 *
 * Not in SUSv4

USE_TRUNCATE(NEWTOY(truncate, "<1s#|c", TOYFLAG_BIN))

config TRUNCATE
	bool "truncate"
	default y
	help
	  usage: truncate [-c] -s file...
	  Set length of file(s), extending sparsely if necessary.

	  -c	Don't create file if it doesn't exist.
	  -s	New size
*/

#include "toys.h"

DEFINE_GLOBALS(
	long size;
)

#define TT this.truncate

static void do_truncate(int fd, char *name)
{
	if (fd<0) return;
	if (ftruncate(fd, TT.size)) {
		perror_msg("failed to set '%s' to '%ld'", name, TT.size);
		toys.exitval = EXIT_FAILURE;
	}
}

void truncate_main(void)
{
	int cr = !(toys.optflags&1);

	// Create files with mask rwrwrw.
	// Nonexistent files are only an error if we're supposed to create them.
	loopfiles_rw(toys.optargs, O_WRONLY|(cr ? O_CREAT : 0), 0666, cr,
		do_truncate);
}