diff options
| author | user <user@clank> | 2026-07-16 07:41:04 +0200 |
|---|---|---|
| committer | user <user@clank> | 2026-07-16 07:41:04 +0200 |
| commit | c303bcde76d0d90a5c6e623466fd3c8d7ff3a072 (patch) | |
| tree | 2fbaac3afc7c5c1e3212746223753b379cd6a80b /c/wc.c | |
| parent | tools: wc, head, and an argc/argv demo (args) + libc.c helpers (diff) | |
| download | gbos-c303bcde76d0d90a5c6e623466fd3c8d7ff3a072.tar.gz gbos-c303bcde76d0d90a5c6e623466fd3c8d7ff3a072.tar.xz gbos-c303bcde76d0d90a5c6e623466fd3c8d7ff3a072.zip | |
libc: option parsing (hasflag/optval); wc -l/-w/-c, head -n N
- hasflag(argv,argc,f): single-char flag present (-f or within -abc)
- optval(argv,argc,opt): value for -opt (-n 5 or -n5)
- wc supports -l/-w/-c (default all); head supports -n N (and bare N)
Diffstat (limited to '')
| -rw-r--r-- | c/wc.c | 23 |
1 files changed, 14 insertions, 9 deletions
@@ -1,20 +1,25 @@ #include "gbos.h" -/* wc: count lines, words, chars of stdin (like `wc`). */ +/* wc [-l] [-w] [-c]: count lines, words, chars of stdin (default: all). */ void main(void) { + char *argv[8]; + unsigned char argc = argv_parse(argv, 8); + unsigned char wl = hasflag(argv, argc, 'l'); + unsigned char ww = hasflag(argv, argc, 'w'); + unsigned char wch = hasflag(argv, argc, 'c'); unsigned int lines = 0, words = 0, chars = 0; - unsigned char inword = 0; + unsigned char inword = 0, first = 1; char c; + if (!wl && !ww && !wch) { wl = ww = wch = 1; } for (;;) { c = readc(); if (c == EOF) break; chars++; if (c == '\n') lines++; - if (c == ' ' || c == '\n' || c == '\r' || c == '\t') { - inword = 0; - } else if (!inword) { - inword = 1; - words++; - } + if (c == ' ' || c == '\n' || c == '\r' || c == '\t') inword = 0; + else if (!inword) { inword = 1; words++; } } - putu(lines); putc(' '); putu(words); putc(' '); putu(chars); nl(); + if (wl) { putu(lines); first = 0; } + if (ww) { if (!first) putc(' '); putu(words); first = 0; } + if (wch) { if (!first) putc(' '); putu(chars); } + nl(); } |
