Summary Files Commits Branches @commit @diff @stats
path: root / Year 2 / Operating Systems / Pract11 / wc.c
blob: 94627a0bb69291c781b34a57eff52595e254d6f3 (plain) (blame)
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
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

const size_t BUF_SIZE = 1024;

int main(int argc, char* argv[]) {
	if (argc < 2) return 1;

	int fd_in = open(argv[1], O_RDONLY);
	if (fd_in < 0) return 2;

	char buf[BUF_SIZE];
	int actual = read(fd_in, buf, BUF_SIZE);

	int lines = 0, words = 0, bytes = 0;

	while (actual > 0) {
		bytes += actual;
		for (int i = 0; i < actual; i++) {
			if (buf[i] == '\n') {
				lines++;
				if (i == 0 || buf[i-1] == '\n') words--;
			}
			else if (buf[i] == ' ') {
				words++;
				while (buf[i] == ' ') i++;
			}
		}
		actual = read(fd_in, buf, BUF_SIZE);
	}
	words += lines;
	printf("%d %d %d\n", lines, words, bytes);
	return 0;
}