The Seventh Line

Difficulty: ★ ★ ☆ ☆

For me, the scariest part of learning how to program a computer was file access. The problem was the horrid documentation. It introduced both sequential and random file access together without much explanation. So it was with much trepidation that I wrote my first file I/O program. That’s when I realized that the manual was stupid.

In my books and online courses, I teach sequential file access first. I don’t even bother mentioning random access, as introducing the two together is what confused me way back when. With C, a file is read just like any other input. A text file is scooped up one line at a time, which leads to this month’s Exercise.

Your task is to read the seventh line from a named file. Blank lines in the file count. If the file lacks a seventh line, report that it’s missing. Likewise, report when the line is blank or too large to be read.

Here is output from my solution when ran on the file sonnet18:

The seventh line of file 'sonnet18.txt' is:
And every fair from fair sometime declines,

When run on a file without a seventh line, here is the output:

File 'gettysburg.txt' lacks a seventh line

Please try this exercise on your own before you check out my solution.

Leave a Reply