~sircmpwn/ctools

ref: bb5007143abfc22d947c422bfade941e2a741c8c ctools/src/cat.c -rw-r--r-- 1.2 KiB
bb500714Drew DeVault link: add conformance test 2 years ago
                                                                                
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
78
79
80
81
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <getopt.h>
#include <unistd.h>

static void
usage(void)
{
	fprintf(stderr, "usage: cat [-u] [file...]\n");
}

static int
cat(const char *path)
{
	int fd;
	if (path[0] == '-' && path[1] == '\0') {
		fd = STDIN_FILENO;
	} else {
		if ((fd = open(path, O_RDONLY)) < 0) {
			perror(path);
			return 1;
		}
	}

	ssize_t n;
	char buf[BUFSIZ];
	while ((n = read(fd, buf, sizeof(buf))) > 0) {
		ssize_t offs = 0;
		while (offs < n) {
			ssize_t o = write(STDOUT_FILENO, buf, n);
			if (o < 0) {
				perror("write");
				close(fd);
				return 1;
			}
			offs += o;
		}
	}
	close(fd);

	if (n < 0) {
		perror(path);
		return 1;
	}

	return 0;
}

int
main(int argc, char *argv[])
{
	char opt;
	while ((opt = getopt(argc, argv, "u")) != -1) {
		switch (opt) {
		case 'u':
			/* "Write bytes from the input file to the standard
			 * output without delay as each is read", which we were
			 * going to do anyway. */
			break;
		default:
			usage();
			return 1;
		}
	}

	if (optind == argc) {
		optind = 0;
		argc = 1;
		argv = (char *[]){ "-" };
	}

	for (int i = optind; i < argc; ++i) {
		if (cat(argv[i]) > 0) {
			return 1;
		}
	}

	return 0;
}