Text File Statistics Tool (wc clone)
Write your own version of the Unix wc command in C: a tool that counts the lines, words and characters in text files, plus one extra, the length of the longest line. It works on one or many files (printing a total), reads from standard input so it can be used in pipes like cat notes.txt | mywc, and lets you choose what to print with flags such as -l and -w, just like the real wc. It's a classic first C project: you'll learn reading files character by character, keeping state while reading (inside a word or not), command-line options with getopt, error handling with errno, and comparing your results with a real tool.
- Estimate
- ~6h
- Steps
- 6
- Completed by
- 0
- Proposed by
- codeseed.app
stdio.h · getopt
Project roadmap
- 01
Count one file
~1.5hWrite a Counts struct (lines, words, bytes and longest line) and a function that reads a FILE* with fgetc until EOF and fills it: a line ends at each \n, a word starts when a non-space character follows a space (use isspace), and every character read counts as a byte. Print the counts for a file given as an argument. Done when: the counts for a few test files match wc's output.
- 02
Track the longest line
~1hKeep the current line's length while reading, compare it with the longest when a line ends, and also check the last line when the file doesn't end with a newline. Count a tab as moving to the next multiple of 8, as wc -L does. Done when: the longest line matches wc -L for your test files.
- 03
Handle several files and a total
~1hLoop over all file names, printing one line of counts per file followed by the name, and a total line when there's more than one file. When a file can't be opened, print an error with strerror(errno) to stderr, keep going, and exit with status 1 at the end. Align the columns. Done when: running on several files, including a missing one, matches wc's behavior.
- 04
Add options with getopt
~1hUse getopt to support -l (lines), -w (words), -c (bytes) and -L (longest line) in any combination, printing only the chosen counts in wc's order. With no options, print lines, words and bytes. Reject unknown options with a usage message. Done when: every combination of options gives the same output as wc.
- 05
Read from standard input
~0.5hWhen no file names are given, or the name is -, read from stdin, so the tool works in pipes. Done when: cat file.txt | ./mywc -l prints the same as wc -l.
- 06
Test against wc
~1hWrite a Makefile with -Wall -Wextra, and a test script that runs your tool and wc on the same test files (empty, one line without a newline, several spaces and tabs, a large file and a binary file) with each option, and reports any differences. Done when: the test script reports no differences.
Resources
Ready to build this?
Get a GitHub repo and start building. Your AI reviewer checks each step as you go.
Tech stack