How to resolve the algorithm Read a specific line from a file step by step in the Seed7 programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Read a specific line from a file step by step in the Seed7 programming language

Table of Contents

Problem Statement

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

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.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Read a specific line from a file step by step in the Seed7 programming language

Source code in the seed7 programming language

$ include "seed7_05.s7i";
 
const func string: getLine (inout file: aFile, in var integer: lineNum) is func
  result
    var string: line is "";
  begin
    while lineNum > 1 and hasNext(aFile) do
      readln(aFile);
      decr(lineNum);
    end while;
    line := getln(aFile);
  end func;

const proc: main is func
  local
    var string: fileName is "input.txt";
    var file: aFile is STD_NULL;
    var string: line is "";
  begin
    aFile := open(fileName, "r");
    if aFile = STD_NULL then
      writeln("Cannot open " <& fileName);
    else
      line := getLine(aFile, 7);
      if eof(aFile) then
        writeln("The file does not have 7 lines");
      else
        writeln("The 7th line of the file is:");
        writeln(line);
      end if;
    end if;
  end func;

  

You may also check:How to resolve the algorithm Department numbers step by step in the 11l programming language
You may also check:How to resolve the algorithm Solve the no connection puzzle step by step in the Picat programming language
You may also check:How to resolve the algorithm Order two numerical lists step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Bulls and cows step by step in the Smalltalk programming language
You may also check:How to resolve the algorithm Semordnilap step by step in the Bracmat programming language