Some languages have special semantics for obtaining a known line number from a file.



Task

Demonstrate how to obtain the contents of a specific line within a file.

For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (for potential future use within the program if the code were to become embedded).

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.

Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.




/* NetRexx */
options replace format comments java crossref symbols nobinary
 
parse arg inFileName lineNr .
 
if inFileName = '' | inFileName = '.' then inFileName = './data/input.txt'
if lineNr     = '' | lineNr     = '.' then lineNr     = 7
 
do
  lineTxt = readLine(inFileName, lineNr)
  say '<textline number="'lineNr.right(5, 0)'">'lineTxt'</textline>'
catch ex = Exception
  ex.printStackTrace()
end
 
return
 
-- =============================================================================
-- NetRexx/Java programs don't have a special mechanism to seek to a specified line number
-- the simple solution is to iterate through file. (Costly for very large files)
method readLine(inFileName, lineNr) public static signals IOException, FileNotFoundException
 
  lineReader = LineNumberReader(FileReader(File(inFileName)))
  notFound   = isTrue
  lineTxt    = ''
  loop label reading forever
    line = lineReader.readLine()
    select
      when lineReader.getLineNumber() = lineNr then do
        lineTxt  = line
        notFound = isFalse
        leave reading -- terminate I/O loop
        end
      when line = null then do
        leave reading -- terminate I/O loop
        end
      otherwise nop
      end
    finally
      lineReader.close()
    end reading
 
  if notFound then signal RuntimeException('File' inFileName 'does not contain line' lineNr.right(5))
 
  return lineTxt
 
-- =============================================================================
method isTrue() public static returns boolean
  return 1 == 1
-- =============================================================================
method isFalse() public static returns boolean
  return \(1 == 1)
 