Intro to C #2: minigrep
Starter code: minigrep-package.tar
Upload solutions via Moodle as: minigrep.tar
Goals
- More C practice
- Using
fgets
, and learning its limitations - Keep reading those man pages!
Rubric
grep
If you ever want to search for strings in one or a million files in a Unix environment, you should get to know grep.
Let me be more direct: you should get to know grep, period.
Here are some example grep commands:
Reading lines of text with fgets
For your previous assignment, you could do the whole thing reading one
byte (i.e., one char
) at a time from the input file. Thus,
the standard library function fgetc
was exactly what you needed.
But sometimes, you need a whole line of text. In those cases, fgets
is often the right tool. Here's a quick sample of how to use it:
Read the description of fgets
on its man page to answer questions
like: does the newline character get stored in buffer
? is the string
in buffer
always null-terminated? what happens if the line in the
the file is longer than the size of the buffer?
Programming assignment #2: minigrep
For this assignment, you will write a C program minigrep.c
that takes the name of an input file and a search string as command-line
parameters (in that order) and prints to standard output every line of the input file
that contains the search string, preceded by the (1-based) line number of the line.
For example, suppose you have this file named animals.txt
:
Then running your minigrep
program on this file should look
like this:
(When I went looking for animal examples for minigrep, I discovered for the first time, to my great delight, the existence of the dorking chicken. On the other hand, I'm sad that "dorking" here merely refers to the town of Dorking, England, rather than some sort of mysterious chicken activity.)
You may assume that no line of your file contains more than 200 bytes/chars, including the newline character.
Submitting your work
As you did for your first homework assignment,
put all the files you want to submit in a folder named minigrep
(this should
probably just be a single source file minigrep.c
), run
tar cvf minigrep.tar minigrep
, and then submit the tar file via Moodle.
Remember that advice from last time?
- Think ahead of time about error handling. What could go wrong with the command-line or the input file or anything else in your program? What should your program do when those things happen?
- Think ahead of time about testing. What special cases should you test? How can you test them?
- Assume that each line ends either with a newline character
\n
(ASCII 10) or with the end of the file. You'll want your program to work even if the last line doesn't end with\n
.
Have fun!
Keep experimenting! Keep asking questions!