Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practice01 / ex4-wc.c
blob: 29fb5725d54e1ee9429d89f54718fd42cfbd8236 (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
#include <unistd.h> // read, write
#include <fcntl.h> // open, close, O_RDONLY
#include <stdio.h> // printf, perror

int isBlank(char c) {
	return c == ' ' || c == '\n' || c == '\t';
}

// print line, word and byte count
int main(int argc, char* argv[]) {
	int f = open(argv[1], O_RDONLY);
	if (f < 0) {
		perror("open");
		return 1;
	}

	int lines = 0, words = 0, bytes = 0;
	char buf;
	int lastWasBlank = 0;
	while (read(f, &buf, 1)) {
		bytes++;
		if (buf == '\n') lines++;
		if (isBlank(buf)) {
			words += !lastWasBlank;
			lastWasBlank = 1;
		}
		else lastWasBlank = 0;
	}

	close(f);

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