Some languages have special semantics for obtaining a known line number from a file. The task is to demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how to the contents of the seventh line of a file can be obtained, and store this in a variable. If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message. If no special semantics are available for obtaining the required line, it is permissible to read line by line. Note that empty lines are considered and should still be counted,

Read a specific line from a file is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

J

<lang j>readLine=: 4 :0

 (x-1) {:: <;.2 ] 1!:1 boxxopen y

)</lang>

Thus: <lang bash>$ cal 2011 > cal.txt</lang>

<lang j> 7 readLine 'cal.txt'

9 10 11 12 13 14 15  13 14 15 16 17 18 19  13 14 15 16 17 18 19

</lang>

Note that this code assumes that the last character in the file is the line end character, and that the line end character is a part of the line to be retrieved.

Tacit alternative <lang j>require 'files' NB. required for versions before J701 readLineT=: <:@[ {:: 'b'&freads@]</lang> This is not quite equivalent to the code above as it handles cross-platform line-endings and those line end character(s) are removed from the result.

Tcl

This code can deal with very large files with very long lines (up to 1 billion characters in a line should work fine, provided enough memory is available) and will return an empty string when the nth line is empty (as an empty line is still a valid line). <lang tcl>proc getNthLineFromFile {filename n} {

   set f [open $filename]
   while {[incr n -1] > 0} {
       if {[gets $f line] < 0} {
           close $f
           error "no such line"
       }
   }
   close $f
   return $line

}

puts [getNthLineFromFile example.txt 7]</lang> Where it is necessary to provide very fast access to lines of text, it becomes sensible to create an index file describing the locations of the starts of lines so that the reader code can seek directly to the right location. This is rarely needed, but can occasionally be helpful.