commit b9025a01db609ca07fdb0a0b8b10c6404f2d20ff
parent 727a6f6485e014bdd810c73e00329ff2a6a6ff51
Author: NunoSempere <nuno.sempere@protonmail.com>
Date: Sat, 9 Sep 2023 00:02:31 +0200
add usage, start looking into gnu utils
Diffstat:
4 files changed, 25 insertions(+), 16 deletions(-)
diff --git a/README.md b/README.md
@@ -11,9 +11,11 @@ Desiderata
Steps:
-- [ ] Look into how C utilities both read from stdin and from files.
-- [ ] ...
+- [x] Look into how C utilities both read from stdin and from files.
+- [x] Program first version of the utility
- [ ] Compare with other implementations, see how they do it, after I've read my own version
- - Compare with gnu utils,
+ - [ ] Compare with gnu utils,
- Compare with musl/busybox implementations,
- Maybe make some pull requests, if I'm doing something better?
+- [ ] Install to ww, but check that ww is empty (installing to wc2 or smth would mean that you don't save that many keypresses vs wc -w)
+- [ ] ...
diff --git a/makefile b/makefile
@@ -9,7 +9,7 @@ CC=gcc
# Main file
SRC=wc.c
-OUTPUT=wc
+OUT=wc
## Flags
DEBUG= #'-g'
@@ -24,13 +24,14 @@ FORMATTER=clang-format -i -style=$(STYLE_BLUEPRINT)
## make build
build: $(SRC)
- $(CC) $(OPTIMIZED) $(DEBUG) $(SRC) -o $(OUTPUT)
+ $(CC) $(OPTIMIZED) $(DEBUG) $(SRC) -o $(OUT)
format: $(SRC)
$(FORMATTER) $(SRC)
-test: $(OUTPUT)
- /bin/echo -e "123\n45 67" | ./$(OUTPUT)
+test: $(OUT)
+ /bin/echo -e "123\n45 67" | ./$(OUT)
/bin/echo -n "" | ./wc
- ./$(OUTPUT) $(SRC)
- ./$(OUTPUT) nonexistent_file || true
+ /bin/echo " xx x" | ./$(OUT) -w
+ ./$(OUT) $(SRC)
+ ./$(OUT) nonexistent_file || true
diff --git a/wc b/wc
Binary files differ.
diff --git a/wc.c b/wc.c
@@ -6,17 +6,22 @@ int process_fn(int fn)
{
char c[1];
int seen_word=0;
- int seen_sep=0;
+ int seen_sep_after_word=0;
int num_words = 0;
while (read(fn, c, sizeof(c)) > 0) {
- if(*c == '\n' || *c == ' ' || *c == '\t'){
- seen_sep = 1;
- } else {
+ if(*c != '\n' && *c != ' ' && *c != '\t'){
seen_word = 1;
+ } else if(seen_word) {
+ seen_sep_after_word = 1;
+ } else {
+ // see a separator, but haven't seen a word: do nothing
+ // exercise: what happens if you only track seen_sep,
+ // instead of seen_sep_after_word?
+ // test with: $ echo " x x" | ./wc
}
- if(seen_word && seen_sep){
+ if(seen_word && seen_sep_after_word){
num_words++;
- seen_sep = seen_word = 0;
+ seen_sep_after_word = seen_word = 0;
}
}
if(seen_word){
@@ -38,7 +43,8 @@ int main(int argc, char** argv)
}
return process_fn(fileno(fp));
} else {
- printf("To do");
+ printf("Usage: ww file.txt\n");
+ printf(" or: cat file.txt | ww\n");
}
return 0;
}