Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practicum1 / wc.c
blob: fc0cee5757fbc55d71aa8774af6958d0db13c0dd (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
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
	int f = open(argv[1], O_RDONLY);
	if (f == -1) return 1;

	char buf;
	int prevNotSpace = 1;
	int bytes = 0, newlines = 0, words = 0;
	while (read(f, &buf, 1)) {
		bytes++;
		if (buf == '\n') {
			newlines++;
			words++;
		}
		if (buf == ' ' || buf == '\t') {
			words += prevNotSpace;
			prevNotSpace = 0;
		}
		else prevNotSpace = 1;
	}

	close(f);
	printf("%d %d %d %s\n", newlines, words, bytes, argv[1]);
}