summaryrefslogtreecommitdiff
path: root/direct-append.c
blob: 2b782ffa5cab8a82292b42741c6a0e38aeaa4754 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
 * Append some random characters to a file
 *
 * Just a small tool to debug inotify
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/stat.h>
#include <fcntl.h>

#define DEFAULT_N_CHARS 1024

static char get_random_printable_char(void)
{
	int fd;
	char ret;

	fd = open("/dev/urandom", O_RDONLY);
	if (fd < 0) {
		perror("open");
		exit(EXIT_FAILURE);
	}

	do {
		read(fd, &ret, sizeof(ret));
	} while (ret < 0x20 || ret > 0x7e);

	close(fd);

	return ret;
}

int main(int argc, char *argv[])
{
	int fd, n_chars, i;
	char *str;

	if (argc < 3) {
		fprintf(stderr, "Usage: %s <file> <n_chars>\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	/* Open the file, create it in case it doesn't exist */
	if ((fd = open(argv[1], O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) < 0) {
		perror("open");
		exit(EXIT_FAILURE);
	}

	if (lseek(fd, 0, SEEK_END) < 0) {
		perror("lseek");
		exit(EXIT_FAILURE);
	}

	n_chars = strtoul(argv[2], NULL, 0);
	if (n_chars <= 0) {
		fprintf(stderr, "Invalid number of characters: %d\n", n_chars);
		n_chars = DEFAULT_N_CHARS;
	}

	str = malloc(n_chars * sizeof(char));
	if (!str) {
		perror("malloc");
		exit(EXIT_FAILURE);
	}

	for (i = 0; i < n_chars; i++)
		str[i] = get_random_printable_char();

	write(fd, str, n_chars);
	free(str);
	close(fd);

	exit(EXIT_SUCCESS);
}