fgets Function

The function we will use to actually read in lines from our file is the fgets function. We used it before with the stdin stream to read a string of data from the keyboard into a buffer. This time, instead of using stdin as our input stream, we will use our file handle.

It is hard to say how big our input buffer should be. It should be long enough to hold an entire line of our input file. We can use 500 characters and change it later if that isn't long enough. Of course we need to use some sort of loop to keep bringing in lines from the file for processing by our program. A while loop is one way we can do this (later on we present another way), but we need it to terminate when the end of the file is reached.

The function we use to test whether the end of file has come or not is feof, from the stdio library. It takes our file handle as a parameter and returns true or false according to the standard boolean convention, depending on whether the end of file has come or not.

To loop through the file, reading a line at a time into a buffer until the EOF (end of file) condition becomes true, we need to add the following lines of code to our program:

char buffer[500];

while (!feof(weblog))
{
    fgets(buffer,500,weblog);
    //process the line stored in the buffer 
}

Observe how simple file handling is in C! An easy exercise at this point is to use your knowledge developed up to this point to display each line of the file on the screen as it is read in (hint: only one line needs to be added to the program).