From a594346d7e2ca97717cae7e705c00d6fe0b9a460 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Sat, 2 Dec 2023 18:10:23 +0200 Subject: [SP/P01] Solved exercises from first practice (again) --- Year 3/System programming/Practice01/ex4-wc.c | 33 +++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Year 3/System programming/Practice01/ex4-wc.c (limited to 'Year 3/System programming/Practice01/ex4-wc.c') diff --git a/Year 3/System programming/Practice01/ex4-wc.c b/Year 3/System programming/Practice01/ex4-wc.c new file mode 100644 index 0000000..29fb572 --- /dev/null +++ b/Year 3/System programming/Practice01/ex4-wc.c @@ -0,0 +1,33 @@ +#include // read, write +#include // open, close, O_RDONLY +#include // 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]); +} -- cgit v1.3.1-26-gb76a