Be sure you have read, or at least skimmed, the readings for 4/19, linked from the ``Lecture topics and assignments'' page.
Do the following programming problems. You will end up with at least one code file per problem. Submit your program source by sending mail to bmassing@cs.trinity.edu, with each file as an attachment. Please use a subject line that mentions the course number and the assignment (e.g., ``csci 1120 homework 6''). You can develop your programs on any system that provides the needed functionality, but I will test them on one of the department's Linux machines, so you should probably make sure they work in that environment before turning them in.
Hello world! There is a German word for worldview that I have forgotten. World without end. Goodbye!
and you search for world, the first and second lines should print. (It's easiest to do the match in a case-sensitive way, so the third line does not match.)
The program should accept two command-line arguments, the first containing the text to search for and the second containing the name of the file to search. (For extra credit, make the program work more like grep, which allows searching any number of files, or none, in which case it searches for the specified text in standard input. If you do this, and more than one file is specified, print matching lines in a way that makes it clear which file they came from. grep does this by preceding each matching line with the name of the file it came from, e.g.,
input.txt: There is a German word for worldview that I have forgotten.
but you may think of some format you like better.)
For this problem, read the file a line at a time, but be as careful as you can about reading text -- it is very easy to read more characters than will fit into the character array you're putting them in. (I usually recommend using the library function fgets for reading text line by line.) If the input file contains lines that are too long, you can just print warning messages about them.
You may find the library function strstr useful.
To do this, I think you will need to read the whole file into memory. There are various ways to do this, but the method I have in mind (for learning purposes) is to read the whole file into memory and then build an array of pointers to individual lines. Here is a function you can use (on Linux systems anyway) to determine how much memory to allocate for the file:
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> /* returns size of file *filename in bytes, or -1 on error */ int filesize(char * filename) { struct stat status; if (stat(filename, &status) == -1) { return -1; } else { return (int) status.st_size; } }