Counting the Lines

Our first task is to dynamically allocate space for the array of pointers. Since there must be a pointer for every line in the weblog, we must count the latter before we can allocate memory for the array.

This is a simple matter of adding a variable of type int to our program and looping through the lines in the weblog file, incrementing this variable for each line.

To accomplish this, we add the following line at the start of our program:

int numLines = 0;

Then we place the following line inside a while loop similar to the one that we already coded up in the previous lesson:

numLines++;

Now that we have reached the end of the weblog file, we must set the file counter back to the beginning again, so that we are ready to actually read the data itself. This is accomplished with the rewind function, as follows-na:

rewind(weblog);