summaryrefslogtreecommitdiff
path: root/fallocate.c
blob: 910d191ff833839801134bd673004c606a89f25f (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
48
49
50
51
52
53
54
55
56
57
58
59
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


#define EXIT_BAD_OPTION 2


void usage(int fd, char * progname)
{
	dprintf(fd, "Usage: %s [-o offset] -l length name\n", progname);
}


int try_fallocate(char * filename, int offset, int length)
{
	int fd = open(filename, O_CREAT|O_WRONLY|O_TRUNC, 0644);
	if (-1 == fd) return -1;
	int res = posix_fallocate(fd, offset, length);
	if (-1 == res) return -1;
	res = close(fd);
	if (-1 == res) return -1;
	return 0;
}


int main(int argc, char * argv[])
{
	int opt;
	int offset = 0;
	int length = 0;
	char * filename;
	while (-1 != (opt = getopt(argc, argv, "o:l:"))) {
		switch (opt) {
		case 'o':
			offset = atoi(optarg);
			break;
		case 'l':
			length = atoi(optarg);
			break;
		default:
			usage(2, argv[0]);
			exit(EXIT_BAD_OPTION);
		}
	}
	if (0 >= length || argc <= optind) {
		usage(2, argv[0]);
		exit(EXIT_BAD_OPTION);
	}
	filename = argv[optind];
	int res = try_fallocate(filename, offset, length);
	if (-1 == res) {
		dprintf(2, "%s: %s: %s\n", argv[0], filename, strerror(errno));
		exit(EXIT_FAILURE);
	}
}