This month’s programming Exercise isn’t as much about file access as it’s about dealing with a situation when no data is available. The task: Read the seventh line from a file.
The approach here is to use sequential file access, which is a topic I mentioned in the Exercise post. The file is read one line at a time, tracking count of the lines as each is read. In my solution, I opted for a BUFSIZ
buffer, which is plenty huge enough to swallow long lines in a text file. Here’s my solution:
2024_08-Exercise.c
#include <stdio.h> int main( int argc, char *argv[] ) { FILE *fh; char buffer[BUFSIZ],*r,*filename; int line; /* check for the command line argument */ if( argc<2 ) { fprintf(stderr,"Please specify a file to examine\n"); return 1; } /* open the file */ filename = argv[1]; /* for readability */ fh = fopen(filename,"r"); if ( fh==NULL ) { fprintf(stderr,"Unable to open file '%s'\n",filename); return 1; } /* read seven lines */ for( line=0; line<7; line++ ) { r = fgets(buffer,BUFSIZ,fh); if( r==NULL ) { printf("File '%s' lacks a seventh line\n",filename); fclose(fh); return 1; } } /* output result */ printf("The seventh line of file '%s' is:\n%s", filename, buffer ); /* clean-up */ fclose(fh); return 0; }
The code first checks for a command line argument, which is assumed to be a text file to open. When missing, an error message is output and the program ends.
When a filename is supplied, it’s opened and read. A for loop counts lines from zero through six, with six being the “seventh” line.
The fgets() function fetches each line, storing it in char array buffer[]
. This function returns NULL when the line isn’t read (probably the end-of-file), in which case an appropriate message is output, the file is closed, and the program ends.
After the loop is complete, the seventh line of the file is stored in buffer
. It’s output. The file is closed. The program ends.
Here’s a successful sample run of my solution:
./a.out declaration.txt
The seventh line of file 'declaration.txt' is:
He has refused to pass other Laws for the accommodation of large districts of people, unless those people would relinquish the right of Representation in the Legislature, a right inestimable to them and formidable to tyrants only.
The code is able to handle the long line of text. Here’s a run when the file lacks a seventh line:
./a.out gettysburg.txt
File 'gettysburg.txt' lacks a seventh line
If the seventh line is blank, then a blank line is output. I suppose I could have tested for this condition and output a message, but I didn’t bother.
Finally, a test when the user forgets to supply a filename argument:
./a.out
Please specify a file to examine
The key to this solution is the fgets() function, which reads in lines of text and returns NULL on an error or the EOF. The challenge is to handle the error conditions of missing filenames and text files without a seventh line. I hope your solution met with success.