add usage, start looking into gnu utils

This commit is contained in:
NunoSempere 2023-09-09 00:02:31 +02:00
parent 727a6f6485
commit b9025a01db
4 changed files with 25 additions and 16 deletions

View File

@ -11,9 +11,11 @@ Desiderata
Steps: 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 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, - Compare with musl/busybox implementations,
- Maybe make some pull requests, if I'm doing something better? - 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)
- [ ] ...

View File

@ -9,7 +9,7 @@ CC=gcc
# Main file # Main file
SRC=wc.c SRC=wc.c
OUTPUT=wc OUT=wc
## Flags ## Flags
DEBUG= #'-g' DEBUG= #'-g'
@ -24,13 +24,14 @@ FORMATTER=clang-format -i -style=$(STYLE_BLUEPRINT)
## make build ## make build
build: $(SRC) build: $(SRC)
$(CC) $(OPTIMIZED) $(DEBUG) $(SRC) -o $(OUTPUT) $(CC) $(OPTIMIZED) $(DEBUG) $(SRC) -o $(OUT)
format: $(SRC) format: $(SRC)
$(FORMATTER) $(SRC) $(FORMATTER) $(SRC)
test: $(OUTPUT) test: $(OUT)
/bin/echo -e "123\n45 67" | ./$(OUTPUT) /bin/echo -e "123\n45 67" | ./$(OUT)
/bin/echo -n "" | ./wc /bin/echo -n "" | ./wc
./$(OUTPUT) $(SRC) /bin/echo " xx x" | ./$(OUT) -w
./$(OUTPUT) nonexistent_file || true ./$(OUT) $(SRC)
./$(OUT) nonexistent_file || true

BIN
wc

Binary file not shown.

20
wc.c
View File

@ -6,17 +6,22 @@ int process_fn(int fn)
{ {
char c[1]; char c[1];
int seen_word=0; int seen_word=0;
int seen_sep=0; int seen_sep_after_word=0;
int num_words = 0; int num_words = 0;
while (read(fn, c, sizeof(c)) > 0) { while (read(fn, c, sizeof(c)) > 0) {
if(*c == '\n' || *c == ' ' || *c == '\t'){ if(*c != '\n' && *c != ' ' && *c != '\t'){
seen_sep = 1;
} else {
seen_word = 1; 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++; num_words++;
seen_sep = seen_word = 0; seen_sep_after_word = seen_word = 0;
} }
} }
if(seen_word){ if(seen_word){
@ -38,7 +43,8 @@ int main(int argc, char** argv)
} }
return process_fn(fileno(fp)); return process_fn(fileno(fp));
} else { } else {
printf("To do"); printf("Usage: ww file.txt\n");
printf(" or: cat file.txt | ww\n");
} }
return 0; return 0;
} }