Read a specific line from a file: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(add julia example)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(113 intermediate revisions by 66 users not shown)
Line 1:
{{task}}
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 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. Note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
 
=={{header|Ada}}==
 
;Task:
A github repository was created for this solution https://github.com/mulander/read_a_specific_line_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).
The repository contains test cases for specific file types the program might be run against.
 
If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message.
Based on the task description the following requirements were identified
* Display a specific message for a file having fewer than 7 lines
* Display a specific message if the 7th line is empty
* Display a specific message if the 7th line is too big to be retrieved and stored in memory
* Acquire the 7th line of a file, using built-in language features/standard libraries if accessible
* Store the retrieved line in a variable/memory location
 
If no special semantics are available for obtaining the required line,   it is permissible to read line by line.
The following undefined behavior was identified and addressed
* The task description does not define an empty line. The program assumes that an empty line contains only a line break character. A line containing whitespace (' ', '\t') is not considered empty.
* Things considered an error in execution are printed out to stderr
* In case of an encountered error the return code of the program is changed to Failure (1)
 
Note that empty lines are considered and should still be counted.
In order to ease testing - the program expects the file name to be provided as the first argument on the command line.
 
Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.
Additional checks are performed by the program
<br><br>
* Tests if the file name was provided on the command line
* Tests if the it is possible to open the provided file with read access
 
=={{header|11l}}==
<lang ada>with Ada.Command_Line,
<syntaxhighlight lang="11l">V f = File(‘input.txt’)
Ada.Text_IO;
V line = 3
 
L 0 .< line - 1
procedure Rosetta_Read is
f.read_line()
use Ada.Command_Line, Ada.Text_IO;
print(f.read_line())</syntaxhighlight>
 
=={{header|Action!}}==
Source : File_Type;
In the following solution the input file is loaded from H6 drive. Altirra emulator automatically converts CR/LF character from ASCII into 155 character in ATASCII charset used by Atari 8-bit computer when one from H6-H10 hard drive under DOS 2.5 is used.
begin
<syntaxhighlight lang="action!">BYTE FUNC ReadLine(CHAR ARRAY fname CARD index CHAR ARRAY result)
CHAR ARRAY line(255)
CARD curr
BYTE status,dev=[1]
 
Close(dev)
if Argument_Count /= 1 then
Open(dev,fname,4)
Put_Line (File => Standard_Error,
curr=1 status=1
Item => "Usage: " & Command_Name & " file_name");
WHILE Eof(dev)=0
Set_Exit_Status (Failure);
DO
return;
InputSD(dev,line)
end if;
IF curr=index THEN
SCopy(result,line)
status=0
EXIT
FI
curr==+1
OD
Close(dev)
RETURN (status)
 
PROC Test(CHAR ARRAY fname CARD index)
declare
CHAR ARRAY result(255)
File_Name : String renames Argument (Number => 1);
BYTE beginstatus
Open (File => Source,
Mode => In_File,
Name => File_Name);
exception
when others =>
Put_Line (File => Standard_Error,
Item => "Can not open '" & File_Name & "'.");
Set_Exit_Status (Failure);
return;
end;
 
PrintF("Reading %U line...%E",index)
Set_Line (File => Source,
status=ReadLine(fname,index,result)
To => 7);
IF status=0 THEN
IF result(0)=0 THEN
PrintF("%U line is empty.%E%E",index)
ELSE
PrintF("%U line is:%E""%S""%E%E",index,result)
FI
ELSEIF status=1 THEN
PrintF("File contains less than %U lines.%E%E",index)
FI
RETURN
 
PROC Main()
CHAR ARRAY fname="H6:READ__96.ACT"
 
PrintF("Reading ""%S""...%E%E",fname)
Test(fname,7)
Test(fname,24)
Test(fname,50)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Read_a_specific_line_from_a_file.png Screenshot from Atari 8-bit computer]
<pre>
Reading "H6:READ__96.ACT"...
 
Reading 7 line...
7 line is:
" Open(dev,fname,4)"
 
Reading 24 line...
24 line is:
" BYTE status"
 
Reading 50 line...
File contains less than 50 lines.
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Rosetta_Read is
File : File_Type;
begin
Open (File => File,
Mode => In_File,
Name => "rosetta_read.adb");
Set_Line (File, To => 7);
 
declare
Line_7 : constant String := Get_Line (File => Source);
begin
if Line_7'Length = 0 then
Line 69 ⟶ 110:
end if;
end;
 
Close (File);
exception
when End_Error =>
Put_Line (File"The =>file Standard_Error,contains fewer than 7 lines.");
Close (File);
Item => "The file contains fewer than 7 lines.");
Set_Exit_Status (Failure);
return;
when Storage_Error =>
Put_Line (File"Line =>7 Standard_Error,is too long to load.");
Close (File);
Item => "Line 7 is too long to load.");
end Rosetta_Read;</syntaxhighlight>
Set_Exit_Status (Failure);
return;
end Rosetta_Read;</lang>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
read_line(text &line, text path, integer n)
{
file f;
 
f_affix(f, .affix(path);
 
while call_n(n), {f_slip, f);
n -= 1;
f_slip(f);
}
 
f_line(f, .line(line);
}
 
Line 102 ⟶ 138:
main(void)
{
if (21 < argc()) {
text line;
 
read_line(line, argv(1), 6);
 
o_("7th line is:\n", line, "\n");
o_text(line);
o_byte('\n');
}
 
return 0;
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<syntaxhighlight lang="algol68"># reads the line with number "number" (counting from 1) #
# from the file named "file name" and returns the text of the #
# in "line". If an error occurs, the result is FALSE and a #
# message is returned in "err". If no error occurs, TRUE is #
# returned #
PROC read specific line = ( STRING file name
, INT number # line 7 #
, REF STRING line
, REF STRING err
)BOOL:
IF FILE input file;
line := "";
open( input file, file name, stand in channel ) /= 0
THEN
# failed to open the file #
err := "Unable to open """ + file name + """";
FALSE
ELSE
# file opened OK #
err := "";
BOOL at eof := FALSE;
# set the EOF handler for the file #
on logical file end( input file
, ( REF FILE f )BOOL:
BEGIN
# note that we reached EOF on the #
# latest read #
at eof := TRUE;
 
# return TRUE so processing can continue #
TRUE
END
);
INT line number := 0;
STRING text;
WHILE line number < number
AND NOT at eof
DO
get( input file, ( text, newline ) );
line number +:= 1
OD;
# close the file #
close( input file );
# return the line or an error message depending on whether #
# we got a line with the required number or not #
IF line number = number
THEN
# got the required line #
line := text;
TRUE
ELSE
# not enough lines in the file #
err := """" + file name + """ is too short";
FALSE
FI
FI; # read specific line #
main:(
# read the seventh line of this source and print it #
# (or an error message if we can't) #
STRING line;
STRING err;
IF read specific line( "read-specific-line.a68", 7, line, err )
THEN
# got the line #
print( ( "line seven is: """ + line + """", newline ) )
ELSE
# got an error #
print( ( "unable to read line: """ + err + """" ) )
FI
)</syntaxhighlight>
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
#define MAX_LINE_SIZE 1000
main:
v=0, fd=0
fsearch("-r $'\n'","archivo.txt")(v)
fopen(OPEN_READ,"archivo.txt")(fd)
{"Line #7 = "}, fgetsline(fd,MAX_LINE_SIZE,7,v), println
try
fgetsline(fd,MAX_LINE_SIZE,10,v),
catch(e)
{"Error search line (code=",e,"): "},get str error
finish
println
fclose(fd)
exit(0)
</syntaxhighlight>
{{out}}
<pre>
Line #7 = fila 6,1,2,3,4,5,6,7,8,9,10
Error search line (code=101): GET ROW'MARK OVERFLOW
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">lineToRead: 3
 
lineRead: get read.lines "myfile.txt" lineToRead
 
print lineRead</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">FileReadLine, OutputVar, filename.txt, 7
if ErrorLevel
MsgBox, There was an error reading the 7th line of the file</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
#usage: readnthline.awk -v lineno=6 filename
 
FNR==lineno { storedline=$0; found++ }
 
END {if(found<1){print "ERROR: Line",lineno,"not found"}</lang>
END {
if (found < 1) {
print "ERROR: Line", lineno, "not found"
exit 1
}
print storedline
}
</syntaxhighlight>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">f = freefile
filename$ = "input.txt"
open f, filename$
 
lineapedida = 7
cont = 0
while not (eof(f))
linea$ = readline(f)
cont += 1
if cont = lineapedida then
if trim(linea$) = "" then print "The 7th line is empty" else print linea$
exit while
end if
end while
if cont < lineapedida then print "There are only "; cont; " lines in the file"
close f
end</syntaxhighlight>
 
==={{header|OxygenBasic}}===
library OOP
<syntaxhighlight lang="text">
uses stringutil
new Textarray t
t.load "t.txt"
print t.line 7
' print t.lineCount
del t
</syntaxhighlight>
 
==={{header|QBasic}}===
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">f = FREEFILE
OPEN "input.txt" FOR INPUT AS #f
 
lineapedida = 7
cont = 0
DO WHILE NOT EOF(f)
LINE INPUT #f, linea$
cont = cont + 1
IF cont = lineapedida THEN
IF linea$ = "" THEN PRINT "The 7th line is empty" ELSE PRINT linea$
EXIT DO
END IF
LOOP
IF cont < lineapedida THEN PRINT "There are only "; cont; " lines in the file"
CLOSE #1</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">LET filename$ = "input.txt"
OPEN #1: NAME filename$, ORG TEXT, ACCESS INPUT, CREATE OLD
 
LET lineapedida = 7
LET cont = 0
DO
LINE INPUT #1: linea$
LET cont = cont + 1
IF cont = lineapedida THEN
IF TRIM$(linea$) = "" THEN PRINT "The 7th line is empty" ELSE PRINT linea$
EXIT DO
END IF
LOOP UNTIL END #1
IF cont < lineapedida THEN PRINT "There are only "; cont; " lines in the file"
CLOSE #1
END</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">filename$ = "input.txt"
open filename$ for reading as #1
 
lineapedida = 7
cont = 0
while not eof(#1)
line input #1 linea$
cont = cont + 1
if cont = lineapedida then
if trim$(linea$) = "" then print "The 7th line is empty" else print linea$ : fi
break
end if
wend
if cont < lineapedida print "There are only ", cont, " lines in the file"
close #1
end</syntaxhighlight>
 
=={{header|Batch File}}==
<syntaxhighlight lang="dos">
@echo off
 
for /f "skip=6 tokens=*" %%i in (file.txt) do (
set line7=%%i
goto break
)
:break
echo Line 7 is: %line7%
pause>nul
</syntaxhighlight>
{{in}}
<pre>
This is line 1.
This is line 2.
This is line 3. This line has special characters !@#$%^&*()
This is line 4. The next line is blank
 
This is line 6. This line has trailing spaces.
This is line 7
This is line 8
etc...
</pre>
{{out}}
<pre>
Line 7 is: This is line 7
</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> filepath$ = @lib$ + "..\licence.txt"
requiredline% = 7
Line 139 ⟶ 401:
IF ASCtext$=10 text$ = MID$(text$,2)
PRINT text$</langsyntaxhighlight>
 
=={{header|C}}==
Mmap file and search for offsets to certain line number. Since mapped file really is memory, there's no extra storage procedure once offsets are found.
<langsyntaxhighlight lang="c">#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
Line 208 ⟶ 470:
 
return ret;
}</langsyntaxhighlight>
 
===Alternate Version===
 
This version does not rely on POSIX APIs such as <tt>mmap</tt>, but rather sticks to ANSI C functionality. This version also works with non-seekable files, so it can be fed by a pipe. It performs limited but adequate error checking. That is, <tt>get_nth_line</tt> returns NULL on all failures, and the caller can distinguish EOF, file read error and out of memory by calling <tt>feof()</tt> and <tt>ferror()</tt> on the input file.
 
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
#define BUF_SIZE ( 256 )
 
char *get_nth_line( FILE *f, int line_no )
{
char buf[ BUF_SIZE ];
size_t curr_alloc = BUF_SIZE, curr_ofs = 0;
char *line = malloc( BUF_SIZE );
int in_line = line_no == 1;
size_t bytes_read;
 
/* Illegal to ask for a line before the first one. */
if ( line_no < 1 )
return NULL;
 
/* Handle out-of-memory by returning NULL */
if ( !line )
return NULL;
 
/* Scan the file looking for newlines */
while ( line_no &&
( bytes_read = fread( buf, 1, BUF_SIZE, f ) ) > 0 )
{
int i;
 
for ( i = 0 ; i < bytes_read ; i++ )
{
if ( in_line )
{
if ( curr_ofs >= curr_alloc )
{
curr_alloc <<= 1;
line = realloc( line, curr_alloc );
 
if ( !line ) /* out of memory? */
return NULL;
}
line[ curr_ofs++ ] = buf[i];
}
 
if ( buf[i] == '\n' )
{
line_no--;
 
if ( line_no == 1 )
in_line = 1;
if ( line_no == 0 )
break;
}
}
}
 
/* Didn't find the line? */
if ( line_no != 0 )
{
free( line );
return NULL;
}
 
/* Resize allocated buffer to what's exactly needed by the string
and the terminating NUL character. Note that this code *keeps*
the terminating newline as part of the string.
*/
line = realloc( line, curr_ofs + 1 );
if ( !line ) /* out of memory? */
return NULL;
 
/* Add the terminating NUL. */
line[ curr_ofs ] = '\0';
 
/* Return the line. Caller is responsible for freeing it. */
return line;
}
 
 
/* Test program. Prints out the 7th line of input from stdin, if any */
int main( int argc, char *argv[] )
{
char *line7 = get_nth_line( stdin, 7 );
 
if ( line7 )
{
printf("The 7th line of input was:\n%s\n", line7 );
free( line7 );
} else
{
printf("Did not find the 7th line of input. Reason: ");
if ( feof( stdin ) )
puts("End of file reached.");
else if ( ferror( stdin ) )
puts("Error reading input.");
else
puts("Out of memory.");
}
 
return 0;
}
</syntaxhighlight>
 
=={{header|C sharp}}==
 
<syntaxhighlight lang="c sharp">using System;
using System.IO;
 
namespace GetLine
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(GetLine(args[0], uint.Parse(args[1])));
}
 
private static string GetLine(string path, uint line)
{
using (var reader = new StreamReader(path))
{
try
{
for (uint i = 0; i <= line; i++)
{
if (reader.EndOfStream)
return string.Format("There {1} less than {0} line{2} in the file.", line,
((line == 1) ? "is" : "are"), ((line == 1) ? "" : "s"));
 
if (i == line)
return reader.ReadLine();
 
reader.ReadLine();
}
}
catch (IOException ex)
{
return ex.Message;
}
catch (OutOfMemoryException ex)
{
return ex.Message;
}
}
 
throw new Exception("Something bad happened.");
}
}
}</syntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight C++lang="cpp">#include <string>
#include <fstream>
#include <iostream>
Line 244 ⟶ 660:
return 1 ;
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">(defn read-nth-line
"Read line-number from the given text file. The first line has the number 1."
[file line-number]
(with-open [rdr (clojure.java.io/reader file)]
(nth (line-seq rdr) (dec line-number))))</syntaxhighlight>
 
{{out}}
<pre>user=> (read-nth-line "/tmp/test.txt" 7)
"foo"</pre>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun read-nth-line (file n &aux (line-number 0))
"Read the nth line from a text file. The first line has the number 1"
(assert (> n 0) (n))
Line 259 ⟶ 686:
if (and line (= line-number n))
do (return line))))
</syntaxhighlight>
</lang>
 
Example call:
Line 265 ⟶ 692:
"foo"
 
=={{header|C sharpD}}==
simply
 
<syntaxhighlight lang="d">
<lang C sharp>using System;
void main() {
using System.IO;
import std.stdio, std.file, std.string;
 
auto file_lines = readText("input.txt").splitLines();
namespace GetLine
//file_lines becomes an array of strings, each line is one element
{
writeln((file_lines.length > 6) ? file_lines[6] : "line not found");
internal class Program
}
{
</syntaxhighlight>
private static void Main(string[] args)
{
Console.WriteLine(GetLine(args[0], uint.Parse(args[1])));
}
 
private static string GetLine(string path, uint line)
{
using (var reader = new StreamReader(path))
{
try
{
for (uint i = 0; i <= line; i++)
{
if (reader.EndOfStream)
return string.Format("There {1} less than {0} line{2} in the file.", line,
((line == 1) ? "is" : "are"), ((line == 1) ? "" : "s"));
 
or, line by line
if (i == line)
<syntaxhighlight lang="d">import std.stdio;
return reader.ReadLine();
 
reader.ReadLine();
}
}
catch (IOException ex)
{
return ex.Message;
}
catch (OutOfMemoryException ex)
{
return ex.Message;
}
}
 
throw new Exception("Something bad happened.");
}
}
}</lang>
 
=={{header|D}}==
<lang d>import std.stdio;
 
void main() {
Line 334 ⟶ 725:
writefln("the file only contains %d lines", countLines);
}
}</langsyntaxhighlight>
<pre>
line 7: foreach (char[] line; f.byLine()) {</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{Trans|Pascal}}
<syntaxhighlight lang="delphi">
program Read_a_specific_line_from_a_file;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils;
 
function ReadLine(position: Cardinal; FileName: TFileName): string;
begin
Result := '';
 
if not FileExists(FileName) then
raise Exception.Create('Error: File does not exist.');
 
var F: TextFile;
var line: string;
AssignFile(F, FileName);
Reset(F);
for var _ := 1 to position do
begin
if Eof(F) then
begin
CloseFile(F);
 
raise Exception.Create(Format('Error: The file "%s" is too short. Cannot read line %d',
[FileName, position]));
end;
 
Readln(F, line);
end;
CloseFile(F);
Result := line;
end;
 
begin
Writeln(ReadLine(7, 'test'));
Readln;
end.</syntaxhighlight>
 
=={{header|Elixir}}==
The idea is to stream the file, filter the elements and get the remaining element. If does not exist, nil will be throw and we will pattern match with print_line(_). If the value exists, it will match print_line({value, _line_number}) and the value of the line will be printed.
<syntaxhighlight lang="elixir">
defmodule LineReader do
def get_line(filename, line) do
File.stream!(filename)
|> Stream.with_index
|> Stream.filter(fn {_value, index} -> index == line-1 end)
|> Enum.at(0)
|> print_line
end
defp print_line({value, _line_number}), do: String.trim(value)
defp print_line(_), do: {:error, "Invalid Line"}
end
</syntaxhighlight>
 
=={{header|Erlang}}==
Using function into_list/1 from [[Read_a_file_line_by_line]].
There is no behaviour specified after printing an error message, so I throw an exception. An alternative would be to continue with a default value?
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( read_a_specific_line ).
 
Line 372 ⟶ 821:
line_nr_error( function_clause ) -> too_few_lines_in_file;
line_nr_error( Error ) -> Error.
</syntaxhighlight>
</lang>
 
{{out}}
Line 389 ⟶ 838:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
open System.IO
 
Line 403 ⟶ 852:
// if not not enough lines available
Console.WriteLine(line)
0</langsyntaxhighlight>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: continuations fry io io.encodings.utf8 io.files kernel
math ;
IN: rosetta-code.nth-line
 
: nth-line ( path encoding n -- str/f )
[ f ] 3dip '[
[ _ [ drop readln [ return ] unless* ] times ]
with-return
] with-file-reader ;
 
: nth-line-demo ( -- )
"input.txt" utf8 7 nth-line [ "line not found" ] unless*
print ;
 
MAIN: nth-line-demo</syntaxhighlight>
 
=={{header|Fortran}}==
A lot of petty annoyances can arise in the attempt to complete the desired action, and so the function does not simply return ''true'' or ''false'', nor does it return some drab integer code that would require an auxiliary array of explanatory texts somewhere... Instead, it returns a message reporting on its opinion, with an ad-hoc scheme. If the first character is a space, all is well, otherwise a ! indicates some severe problem while a + indicates a partial difficulty. The text of the desired record is returned via a parameter, thus the caller can be the one responsible for deciding how much space to provide for it. F2000 has provision for allocating character strings of the needed length, but there is no attempt to use that here as the key requirement is for the length to be decided during the process of the READ statement.
 
The example uses F90 only because the MODULE protocol enables usage of a function without having to re-declare its type in every calling routine. Otherwise this is F77 style. Some compilers become confused or raise an error over the manipulation of a function's name as if it were an ordinary variable. In such a case an auxiliary variable can be used with its value assigned to the function name on exit.<syntaxhighlight lang="fortran"> MODULE SAMPLER !To sample a record from a file. SAM00100
CONTAINS SAM00200
CHARACTER*20 FUNCTION GETREC(N,F,IS) !Returns a status. SAM00300
Careful. Some compilers get confused over the function name's usage. SAM00400
INTEGER N !The desired record number. SAM00500
INTEGER F !Of this file. SAM00600
CHARACTER*(*) IS !Stashed here. SAM00700
INTEGER I,L !Assistants. SAM00800
IS = "" !Clear previous content, even if null...SAM00900
IF (N.LE.0) THEN !Start on errors. SAM01000
WRITE (GETREC,1) "!No record",N !Could never be found. SAM01100
1 FORMAT (A,1X,I0) !Message, number. SAM01200
ELSE IF (F.LE.0) THEN !Obviously wrong? SAM01300
WRITE (GETREC,1) "!No unit number",F!Positive is valid. SAM01400
ELSE IF (LEN(IS).LE.0) THEN !Space awaits? SAM01500
WRITE (GETREC,1) "!String size",LEN(IS) !Nope. SAM01600
ELSE !Otherwise, there is hope. SAM01700
REWIND (F) !Clarify the file position. SAM01800
DO I = 1,N - 1 !Grind up to the desired record. SAM01900
READ (F,2,END=3) !Ignoring any content. SAM02000
END DO !Are we there yet? SAM02100
READ (F,2,END = 3) L,IS(1:MIN(L,LEN(IS))) !At last. SAM02200
2 FORMAT (Q,A) !Q = characters yet unread. SAM02300
IF (L.LT.LEN(IS)) IS(L + 1:) = "" !Clear the tail. SAM02400
IF (L.GT.LEN(IS)) THEN !Now for more silliness.SAM02500
WRITE (GETREC,1) "+Length",L !Too long to fit in IS. SAM02600
ELSE IF (L.LE.0) THEN !A zero-length record SAM02700
WRITE (GETREC,1) "+Null" !Is not the same SAM02800
ELSE IF (IS.EQ."") THEN !As a record SAM02900
WRITE (GETREC,1) "+Blank",L !Containing spaces. SAM03000
ELSE !But otherwise, SAM03100
WRITE (GETREC,1) " Length",L !Note the leading space.SAM03200
END IF !Righto, we've decided. SAM03300
END IF !And, no more options. SAM03400
RETURN !So, done. SAM03500
3 WRITE (GETREC,1) "!End on read",I !An alternative ending. SAM03600
END FUNCTION GETREC !That was interesting. SAM03700
END MODULE SAMPLER !Just a sample of possibility. SAM03800
SAM03900
PROGRAM POKE POK00100
USE SAMPLER POK00200
INTEGER ENUFF !Some sizes. POK00300
PARAMETER (ENUFF = 666) !Sufficient? POK00400
CHARACTER*(ENUFF) STUFF !Lots of memory these days. POK00500
CHARACTER*20 RESULT POK00600
INTEGER MSG,F !I/O unit numbers. POK00700
MSG = 6 !Standard output. POK00800
F = 10 !Chooose a unit number. POK00900
WRITE (MSG,*) " To select record 7 from a disc file." POK01000
POK01100
WRITE (MSG,*) "As a FORMATTED file." POK01200
OPEN (F,FILE="FileSlurpN.for",STATUS="OLD",ACTION="READ") POK01300
RESULT = GETREC(7,F,STUFF) POK01400
WRITE (MSG,1) "Result",RESULT POK01500
WRITE (MSG,1) "Record",STUFF POK01600
1 FORMAT (A,":",A) POK01700
POK01800
CLOSE (F) POK01900
WRITE (MSG,*) "As a random-access unformatted file." POK02000
OPEN (F,FILE="FileSlurpN.for",STATUS="OLD",ACTION="READ", POK02100
1 ACCESS="DIRECT",FORM="UNFORMATTED",RECL=82) !Not 80! POK02200
STUFF = "Cleared." POK02300
READ (F,REC = 7,ERR = 666) STUFF(1:80) POK02400
WRITE (MSG,1) "Record",STUFF(1:80) POK02500
STOP POK02600
666 WRITE (MSG,*) "Can't get the record!" POK02700
END !That was easy. POK02800
</syntaxhighlight>
Output:
<pre>
To select record 7 from a disc file.
As a FORMATTED file.
Result: Length 80
Record: CHARACTER*(*) IS !Stashed here. SAM00700
 
As a random-access unformatted file.
Record: CHARACTER*(*) IS !Stashed here. SAM00700
</pre>
Fortran's file reading counts a null line as a valid record so fortunately, there is no difficulty there. Trailing spaces appear in IS because of fixed-size CHARACTER variables. A length parameter for the length of the record as read (with possible trailing spaces counted) could easily enough be passed back.
 
===Random access===
An entirely different approach is possible if the file is opened for random access, and has fixed-size records. In such a case, <code>READ (F,REC=7,ERR=666) STUFF</code> would suffice (where STUFF was the right size for the record) and if the record did not exist (being beyond the last record of a short file) then label 666 would be jumped to - without that, a crash results. In the ASCII world, text files have varying-length records so the example file reactivates source line sequence numbers of the Fortran fixed-format style and yet again, the source file highlighter doesn't recognise another foible of Fortran layout. Although there are many conventions (the simplest being digits only), here a text name is crammed in to the sequence field of columns 73-80.
 
This results in every line being of the same length with an obvious route towards calculating the location of a random record. But, the actual record length is ''not'' 80, because in the ASCII world, plain text files have their records separated by CR, or CRLF, or LFCR, or CR - depending on the system. Experiment shows that this system (Windows XP) uses CRLF, and so the record length is 8'''2'''. But that's not the end of it. The RECL parameter by default is in terms of the default integer size, which is four bytes, and so the record length cannot be specified correctly! Fortunately, the Compaq Visual Fortran compiler has an option to specify that the RECL value is to be in bytes, and, invisibly so here, this has been done...
 
Obviously, this only works because of the special nature of the file being read. Other systems offer a filesystem that does not regard record sizes or separators as being a part of the record that is read or written, and in such a case, a CR (or CRLF, or whatever) does not appear amongst the data. Some systems escalate to enabling such random access for varying-length records, or access by a key text rather than a record number (so that a key of "SAM00700" might be specified), and acronyms such as ISAM start appearing.
 
In Fortran 77 there was no verbose REC=''n'' facility, instead one used <syntaxhighlight lang="fortran">READ (F'7) STUFF(1:80)</syntaxhighlight> - that is, an apostrophe even though an at-sign was available - and again the source file highlighting is confused. An interesting alternative was to use the FIND(F'7) statement instead, followed by an ordinary READ (or WRITE) not necessarily specifying the desired record number. The point of this is that the FIND statement would initiate the pre-positioning for the next I/O ''asynchronously'' so that other processing could intervene between it and the READ or WRITE, and in situations more complex than this example, there could be startling changes in performance. If not always positive ones when many files were being accessed on one physical disc drive. Unfortunately, later Fortran extensions have abandoned this statement, while multiprocessing has proliferated.
 
 
The GO TO style of handling mishaps in an I/O statement makes a simple structure difficult - note that the reception area ought not be fallen into by normal execution, thus the STOP. Unfortunately, READ and WRITE statements do not return a result that could be tested in an IF-statement or WHILE-loop, but this can be approached with only a little deformation: <syntaxhighlight lang="fortran"> READ (F,REC = 7,ERR = 666, IOSTAT = IOSTAT) STUFF(1:80)
666 IF (IOSTAT.NE.0) THEN
WRITE (MSG,*) "Can't get the record: code",IOSTAT
ELSE
WRITE (MSG,1) "Record",STUFF(1:80)
END IF</syntaxhighlight>
Where IOSTAT is an integer variable (and also a key word) and this formulation means not having to remember which way the assignment goes; it is left to right. The error code numbers are unlikely to be the same across different systems, so experimentation is in order. It would be much nicer to be able to write something like <code>IF (READ (F,REC = 7, IOSTAT = IOSTAT) STUFF(1:80)) THEN ''etc.''</code> or <code>DO WHILE(''etc.'')</code>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Open "input.txt" For Input As #1
Dim line_ As String
Dim count As Integer = 0
While Not Eof(1)
Line Input #1, line_ '' read each line
count += 1
If count = 7 Then
line_ = Trim(line_, Any !" \t") '' remove any leading or trailing spaces or tabs
If line_ = "" Then
Print "The 7th line is empty"
Else
Print "The 7th line is : "; line_
End If
Exit While
End If
Wend
If count < 7 Then
Print "There are only"; count; " lines in the file"
End If
Close #1
Print
Print "Press any key to quit"
Sleep </syntaxhighlight>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">nthLine[filename, lineNum] :=
{
line = nth[lines[filenameToURL[filename]], lineNum-1]
if line != undef
return line
else
{
println["The file $filename does not contain a line number $lineNum"]
return undef
}
}</syntaxhighlight>
 
=={{header|FutureBasic}}==
Uses FB's openpanel command that opens a dialog window and allows the user to select the file to read.
<syntaxhighlight lang="futurebasic">window 1
 
long i = 1
Str255 s, lineSeven
CFURLRef url
 
url = openpanel 1, @"Select text file"
if ( url )
open "I", 2, url
while ( not eof(2) )
line input #2, s
if ( i == 7 )
lineSeven = s : break
end if
i++
wend
close 2
if ( lineSeven[0] )
print lineSeven
else
print "File did not contain seven lines, or line was empty."
end if
end if
 
HandleEvents</syntaxhighlight>
 
Input text file:
<pre>
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
</pre>
Output:
<pre>
Line 7
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
"bufio"
"errors"
"fmt"
"io"
"os"
)
 
func main() {
if line, err := rsl("input.txt", 7); err == nil {
fmt.Println("7th line:")
fmt.Println(line)
} else {
fmt.Println("rsl:", err)
}
}
}
 
func rsl(fn string, n int) (r string, err error) {
if n < 1 {
return "", errors.New(fmt.SprintfErrorf("Invalidinvalid request: line %d", n))
}
}
f, err := os.Open(fn)
if err != nil {
return "", err
return
}
}
defer f.Close()
bf := bufio.NewReader(f)
var lline intstring
for lnum := 0; lnum < n; lnum++ {
for {
line, isPrefix, err := bf.ReadLineReadString('\n')
if err == io.EOF {
switch llnum {
case 0:
return "", errors.New("Emptyno lines in file.")
case 1:
return "", errors.New("Onlyonly 1 line.")
default:
return "", errors.New(fmt.SprintfErrorf("Onlyonly %d lines", l)lnum)
}
}
}
}
if err != nil {
return "", err
}
}
}
l++
if lline == n"" {
return "", fmt.Errorf("line %d empty", n)
r = string(line)
}
for isPrefix {
return line, nil
line, isPrefix, err = bf.ReadLine()
}</syntaxhighlight>
if err != nil {
return "", err
}
r += string(line)
}
if r == "" {
return "", errors.New(fmt.Sprintf("Line %d empty.", n))
}
break
}
for isPrefix {
line, isPrefix, err = bf.ReadLine()
if err != nil {
return "", err
}
}
}
return // success
}</lang>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def line = null
new File("lines.txt").eachLine { currentLine, lineNumber ->
if (lineNumber == 7) {
Line 483 ⟶ 1,119:
}
}
println "Line 7 = $line"</langsyntaxhighlight>
 
=={{header|Haskell}}==
 
<langsyntaxhighlight Haskelllang="haskell">main :: IO ()
main = do contents <- readFile filename
case drop 6 $ lines contents of
[] -> error "File has less than seven lines"
l:_ -> putStrLn l
where filename = "testfile"</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 499 ⟶ 1,135:
While it is certainly possible to read at file at specific offsets without reading each line via ''seek'', with files using line feed terminated variable length records something has to read the data to determine the 7th record. This solution uses a combination of repeated alternation and generation limiting to achieve this. The counter is simply to discover if there are enough records.
 
<langsyntaxhighlight Iconlang="icon">procedure main()
write(readline("foo.bar.txt",7)|"failed")
end
Line 505 ⟶ 1,141:
procedure readline(f,n) # return n'th line of file f
f := open(\f,"r") | fail # open file
every i := n & line := |read(f) \ n do i -:= 1 # <== here
close(f)
if i = 0 then return line
end</langsyntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight lang="j">readLine=: 4 :0
(x-1) {:: <;.2 ] 1!:1 boxxopen y
)</langsyntaxhighlight>
 
Thus:
<langsyntaxhighlight lang="bash">$ cal 2011 > cal.txt</langsyntaxhighlight>
 
<langsyntaxhighlight 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</langsyntaxhighlight>
 
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'''
<langsyntaxhighlight lang="j">require 'files' NB. required for versions before J701
readLineT=: <:@[ {:: 'b'&freads@]</langsyntaxhighlight>
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.
 
Line 531 ⟶ 1,167:
<tt>example: java -cp . LineNbr7 LineNbr7.java</tt><br>
<tt>output : line 7: public static void main(String[] args) throws Exception {;</tt>
<langsyntaxhighlight lang="java">package linenbr7;
 
import java.io.*;
Line 563 ⟶ 1,199:
}
}
}</langsyntaxhighlight>
 
===Using Java 11===
<syntaxhighlight lang="java">
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
 
public final class ReadSpecificLineFromFile {
 
public static void main(String[] aArgs) throws IOException {
String fileName = "input.txt";
Path filePath = Path.of(fileName);
String seventhLine = Files.lines(filePath).skip(6).findFirst().orElse(ERROR_TOO_FEW_LINES);
String messageToUser = seventhLine.isBlank() ? ERROR_EMPTY_LINE : seventhLine;
System.out.println(messageToUser);
}
private static final String ERROR_TOO_FEW_LINES = "File has fewer than 7 lines";
private static final String ERROR_EMPTY_LINE = "Line 7 is empty";
 
}
</syntaxhighlight>
{{ out }}
<pre>
Either line 7 of the file or the appropriate error message.
</pre>
 
=={{header|jq}}==
Using jq 1.4, one would have to read the entire file in order to extract a particular line.
Since April 24, 2015, however, the task can be accomplished by only reading the lines up to the desired line number.
We accordingly showcase here these recently added features of jq:
* "inputs" - a builtin which produces a stream
* "foreach" - a control structure for iterating over a stream
* "break" - for breaking out of a loop
<syntaxhighlight lang="jq"># Input - a line number to read, counting from 1
# Output - a stream with 0 or 1 items
def read_line:
. as $in
| label $top
| foreach inputs as $line
(0; .+1; if . == $in then $line, break $top else empty end) ;</syntaxhighlight>
'''Example:''' Read line number $line (to be provided on the command line), counting from 1
<syntaxhighlight lang="jq">$line | tonumber
| if . > 0 then read_line
else "$line (\(.)) should be a non-negative integer"
end</syntaxhighlight>
{{out}}
<syntaxhighlight lang="sh">$ jq -n -r 'range(0;20) | tostring' | jq --arg line 10 -n -R -r -f Read_a_specific_line_from_a_file.jq
9</syntaxhighlight>
 
=={{header|Julia}}==
ThisThe short following snippet of code actually stores all the lines infrom the file in an array and displaydisplays the seventh element of the array, returning an error if there is no such element. Since the array is not referenced, it will be garbage collected when needed. The filehandle is closed upon completion of the task, be it successful or not.
<langsyntaxhighlight Julialang="julia">open(readlines, "path/to/file")[7]</juliasyntaxhighlight>
The next function readreads n lines in the file and displaydisplays the last read if possible, or returnreturns a short message. Here again, the filehandle is automatically closed after the task. Note that the first line is returned if a negative number is given as the line number.
<syntaxhighlight lang="julia">function read_nth_lines(stream, num)
Here again, the filehandle is automatically closed after the task.
<lang Julia>function read_nth_lines (stream, num)
for i = 1:num-1
readline(stream)
Line 576 ⟶ 1,262:
result = readline(stream)
print(result != "" ? result : "No such line.")
end</langsyntaxhighlight>
{{Out}}
<pre>julia> open(line -> read_nth_lines(line, 7), "path/to/file")
"Hi, I am the content of the seventh line\n"</pre>
 
=={{header|K}}==
{{works with|ngn/k}}<syntaxhighlight lang=K>(0:"135-0.txt")7
"will have to check the laws of the country where you are located before\r"</syntaxhighlight>
 
Note that line 0 is the first line of the file. If you dislike the concept of a "zeroth line", you should use 7-1 rather than 7 to retrieve the seventh line:
 
<syntaxhighlight lang=K>(0:"135-0.txt")7-1
"www.gutenberg.org. If you are not located in the United States, you\r"</syntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
import java.io.File
 
fun main(args: Array<String>) {
/* The following code reads the whole file into memory
and so should not be used for large files
which should instead be read line by line until the
desired line is reached */
 
val lines = File("input.txt").readLines()
if (lines.size < 7)
println("There are only ${lines.size} lines in the file")
else {
val line7 = lines[6].trim()
if (line7.isEmpty())
println("The seventh line is empty")
else
println("The seventh line is : $line7")
}
}
 
/* Note that 'input.txt' contains the eight lines:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
*/</syntaxhighlight>
 
{{out}}
<pre>
The seventh line is : Line 7
</pre>
 
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">local(f) = file('unixdict.txt')
handle => { #f->close }
local(this_line = string,line = 0)
#f->forEachLine => {
#line++
#line == 7 ? #this_line = #1
#line == 7 ? loop_abort
}
#this_line // 6th, which is the 7th line in the file
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
We read the whole file into memory, and use 'word$( string, number, delimiter)'. Line delimiter is assumed to be CRLF, and the file is assumed to exist at the path given.
<langsyntaxhighlight lang="lb">fileName$ ="F:\sample.txt"
requiredLine =7
 
Line 593 ⟶ 1,339:
if line7$ =chr$( 13) +chr$( 10) or line7$ ="" then notice "Empty line! ( or file has fewer lines)."
 
print line7$</langsyntaxhighlight>
 
=={{header|MathematicaLua}}==
<syntaxhighlight lang="lua">function fileLine (lineNum, fileName)
<lang Mathematica> If[# != EndOfFile , Print[#]]& @ ReadList["file", String, 7] </lang>
local count = 0
for line in io.lines(fileName) do
count = count + 1
if count == lineNum then return line end
end
error(fileName .. " has fewer than " .. lineNum .. " lines.")
end
 
print(fileLine(7, "test.txt"))</syntaxhighlight>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">path := "file.txt":
specificLine := proc(path, num)
local i, input:
for i to num do
input := readline(path):
if input = 0 then break; end if:
end do:
if i = num+1 then printf("Line %d, %s", num, input):
elif i <= num then printf ("Line number %d is not reached",num): end if:
end proc:</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica"> If[# != EndOfFile , Print[#]]& @ ReadList["file", String, 7]</syntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
 
<syntaxhighlight lang="matlab">
<lang Matlab>
eln = 7; % extract line number 7
line = '';
Line 619 ⟶ 1,389:
end;
printf('line %i: %s\n',eln,line);
</langsyntaxhighlight>
<nowiki>Insert non-formatted text here</nowiki>
 
=={{header|MoonScript}}==
{{trans|Lua}}
<syntaxhighlight lang="moonscript">iter = io.lines 'test.txt'
for i=0, 5
error 'Not 7 lines in file' if not iter!
 
print iter!</syntaxhighlight>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">def getline(fname, linenum)
contents = null
try
contents = new(Nanoquery.IO.File).read()
return contents[linenum]
catch
if contents = null
throw new(Exception, "unable to read from file '" + fname + "'")
else
throw new(Exception, "unable to retrieve line " + linenum + " from file: not enough lines")
end
end
end</syntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 675 ⟶ 1,468:
method isFalse() public static returns boolean
return \(1 == 1)
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
 
<syntaxhighlight lang="nim">import strformat
 
proc readLine(f: File; num: Positive): string =
for n in 1..num:
try:
result = f.readLine()
except EOFError:
raise newException(IOError, &"Not enough lines in file; expected {num}, found {n - 1}.")
 
let f = open("test.txt", fmRead)
echo f.readLine(7)
f.close()
</syntaxhighlight>
 
=={{header|OCaml}}==
Line 681 ⟶ 1,490:
OCaml does not provide built-in facilities to obtain a particular line from a file. It only provides a function to read one line from a file from the current position in the input channel [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALinput_line input_line]. We can use this function to get the seventh line from a file, for example as follows:
 
<langsyntaxhighlight lang="ocaml">let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
Line 701 ⟶ 1,510:
 
let () =
print_endline (nth_line 7 Sys.argv.(1))</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
GP is not able to read specific lines, only whole files. For this capability one can use the <code>extern</code>, <code>externstr</code>, or <code>system</code> commands together with, e.g., the [[#AWK|AWK]] solution, or else use the [[#C|C]] solution from within PARI itself.
 
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<langsyntaxhighlight lang="pascal">Program FileTruncate;
 
uses
Line 742 ⟶ 1,554:
Close(myfile);
writeln(line);
end.</langsyntaxhighlight>
Output:
<pre>
Line 749 ⟶ 1,561:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl -s
# invoke as <scriptname> -n=7 [input]
while (<>) { $. == $n and print, exit }
die "file too short\n";</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
No specific mechanism, but simple enough. If the file is suitably small:
<lang perl6>say lines[6] // die "Short file";</lang>
<!--<syntaxhighlight lang="phix">-->
Without an argument, the <tt>lines</tt> function reads filenames from the command line, or defaults to standard input. It then returns a lazy list, which we subscript to get the 7th element. Assuming this code is in a program called <tt>line7</tt>:
<span style="color: #004080;">object</span> <span style="color: #000000;">lines</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_text</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"TEST.TXT"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">GT_LF_STRIPPED</span><span style="color: #0000FF;">)</span>
<pre>$ cal 2011 > cal.txt
<span style="color: #008080;">if</span> <span style="color: #004080;">sequence</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">)>=</span><span style="color: #000000;">7</span> <span style="color: #008080;">then</span>
$ line7 cal.txt
<span style="color: #0000FF;">?</span><span style="color: #000000;">lines</span><span style="color: #0000FF;">[</span><span style="color: #000000;">7</span><span style="color: #0000FF;">]</span>
16 17 18 19 20 21 22 20 21 22 23 24 25 26 20 21 22 23 24 25 26
<span style="color: #008080;">else</span>
$</pre>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"no line 7"</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
For bigger files:
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"TEST.TXT"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"r"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">6</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">gets</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">gets</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (shows -1 if past eof)</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
 
=={{header|Phixmonti}}==
This works even on infinite files because lists are lazy:
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
<pre>$ yes | line7
 
y
argument 1 get "r" fopen var f drop
$</pre>
0
7 for
f fgets number? if f fclose exitfor else nip nip endif
endfor
print /# show -1 if past eof #/</syntaxhighlight>
 
=={{header|PHP}}==
<syntaxhighlight lang="php"><?php
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
function fileLine ($lineNum, $file) {
$count = 0;
while (!feof($file)) {
$count++;
$line = fgets($file);
if ($count == $lineNum) return $line;
}
die("Requested file has fewer than ".$lineNum." lines!");
}
@ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
if (!$fp) die("Input file not found!");
echo fileLine(7, $fp);
?></syntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(in "file.txt"
(do 6 (line))
(or (line) (quit "No 7 lines")) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pli">
<lang PL/I>
declare text character (1000) varying, line_no fixed;
 
Line 785 ⟶ 1,634:
put skip list (text);
next: ;
</syntaxhighlight>
</lang>
 
=={{header|PowershellPL/M}}==
This is written for the original 8080 PL/M compiler and can be run under CP/M or an emulator or clone.
{{works with|Powershell|3.0}}
<br>The name of the file to read and the line number to read should be specified on the command line. E.g., if the source is in a file called READLINE.PLM and has been compiled to READLINE.COM, then the command <code>READLINE READLINE.PLM 7</code> would display the 7th line of the source.
<lang Powershell>
<syntaxhighlight lang="pli">100H: /* READ A SPECIFIC LINE FROM A FILE */
Get-content $File |
Where Readcount -eq 7 |
set-variable -name Line7
</lang>
 
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';
=={{header|Python}}==
DECLARE NL$CHAR LITERALLY '0AH'; /* NEWLINE: CHAR 10 */
<lang python>from itertools import islice
DECLARE EOF$CHAR LITERALLY '26'; /* EOF: CTRL-Z */
/* CP/M BDOS SYSTEM CALL, RETURNS A VALUE */
BDOS: PROCEDURE( FN, ARG )BYTE; DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* CP/M BDOS SYSTEM CALL, NO RETURN VALUE */
BDOS$P: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
EXIT: PROCEDURE; CALL BDOS$P( 0, 0 ); END; /* CP/M SYSTEM RESET */
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS$P( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS$P( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$STRING( .( 0DH, NL$CHAR, '$' ) ); END;
PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
V = N;
W = LAST( N$STR );
N$STR( W ) = '$';
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
FL$EXISTS: PROCEDURE( FCB )BYTE; /* RETURNS TRUE IF THE FILE NAMED IN THE */
DECLARE FCB ADDRESS; /* FCB EXISTS */
RETURN ( BDOS( 17, FCB ) < 4 );
END FL$EXISTS ;
FL$OPEN: PROCEDURE( FCB )BYTE; /* OPEN THE FILE WITH THE SPECIFIED FCB */
DECLARE FCB ADDRESS;
RETURN ( BDOS( 15, FCB ) < 4 );
END FL$OPEN;
FL$READ: PROCEDURE( FCB )BYTE; /* READ THE NEXT RECORD FROM FCB */
DECLARE FCB ADDRESS;
RETURN ( BDOS( 20, FCB ) = 0 );
END FL$READ;
FL$CLOSE: PROCEDURE( FCB )BYTE; /* CLOSE THE FILE WITH THE SPECIFIED FCB */
DECLARE FCB ADDRESS;
RETURN ( BDOS( 16, FCB ) < 4 );
END FL$CLOSE;
 
PR$BYTE: PROCEDURE( B ); /* PRINT B EITHER AS A CHAR OR IN HEX */
DECLARE B BYTE;
PR$HEX: PROCEDURE( H ); /* PRINT A HEX DIGIT */
DECLARE H BYTE;
IF H < 10 THEN CALL PR$CHAR( H + '0' );
ELSE CALL PR$CHAR( ( H - 10 ) + 'A' );
END PR$HEX;
IF B >= ' ' AND B < 7FH AND B <> '$' THEN DO;
/* PRINTABLE CHAR AND NOT A $, SHOW AS A CHARACTER */
CALL PR$CHAR( B );
END;
ELSE DO;
/* NON-PRINTING CHAR OR $ - SHOW IN HEX */
CALL PR$CHAR( '$' );
CALL PR$HEX( SHR( B, 4 ) );
CALL PR$HEX( B AND 0FH );
END;
END PR$BYTE;
 
/* I/O USES FILE CONTROL BLOCKS CONTAINING THE FILE-NAME, POSITION, ETC. */
/* WHEN THE PROGRAM IS RUN, THE CCP WILL FIRST PARSE THE COMMAND LINE AND */
/* PUT THE FIRST PARAMETER IN FCB1, THE SECOND PARAMETER IN FCB2 */
/* BUT FCB2 OVERLAYS THE END OF FCB1 AND THE DMA BUFFER OVERLAYS THE END */
/* OF FCB2, SO WE NEED TO GET THE LINE NUMBER FROM FCB2 FIRST */
 
DECLARE FCB$SIZE LITERALLY '36'; /* SIZE OF A FCB */
DECLARE FCB1 LITERALLY '5CH'; /* ADDRESS OF FIRST FCB */
DECLARE FCB2 LITERALLY '6CH'; /* ADDRESS OF SECOND FCB */
DECLARE DMA$BUFFER LITERALLY '80H'; /* DEFAULT DMA BUFFER ADDRESS */
DECLARE DMA$SIZE LITERALLY '128'; /* SIZE OF THE DMA BUFFER */
 
DECLARE F$PTR ADDRESS, F$CHAR BASED F$PTR BYTE;
 
/* GET THE LINE NUMBER FROM THE SECOND PARAMETER */
DECLARE LINE$NUMBER ADDRESS;
LINE$NUMBER = 0;
DO F$PTR = FCB2 + 1 TO FCB2 + 8;
IF F$CHAR >= '0' AND F$CHAR <= '9' THEN DO;
LINE$NUMBER = ( LINE$NUMBER * 10 ) + ( F$CHAR - '0' );
END;
END;
/* CLEAR THE PARTS OF FCB1 OVERLAYED BY FCB2 */
DO F$PTR = FCB1 + 12 TO FCB1 + ( FCB$SIZE - 1 );
F$CHAR = 0;
END;
 
/* SHOW THE REQUIRED LINE FROM THE FILE, IF THE FILE AND LINE EXIST */
IF NOT FL$EXISTS( FCB1 ) THEN DO; /* THE FILE DOES NOT EXIST */
CALL PR$STRING( .'FILE NOT FOUND$' );CALL PR$NL;
END;
ELSE IF NOT FL$OPEN( FCB1 ) THEN DO; /* UNABLE TO OPEN THE FILE */
CALL PR$STRING( .'UNABLE TO OPEN THE FILE$' );CALL PR$NL;
END;
ELSE DO; /* FILE EXISTS AND OPENED OK - ATTEMPT TO FIND THE LINE */
DECLARE LN ADDRESS, GOT$RCD BYTE, GOT$LINE BYTE, DMA$END ADDRESS;
DMA$END = DMA$BUFFER + ( DMA$SIZE - 1 );
GOT$RCD = FL$READ( FCB1 ); /* GET THE FIRST RECORD */
GOT$LINE = FALSE;
F$PTR = DMA$BUFFER;
LN = 1;
CALL PR$NUMBER( LINE$NUMBER ); CALL PR$STRING( .': <$' );
DO WHILE( GOT$RCD AND LN <= LINE$NUMBER );
IF F$PTR > DMA$END THEN DO;
/* AT THE END OF THE BUFFER - GET THE NEXT RECORD */
GOT$RCD = FL$READ( FCB1 );
F$PTR = DMA$BUFFER;
END;
ELSE IF F$CHAR = NL$CHAR THEN DO; /* END OF LINE */
LN = LN + 1;
IF LN = LINE$NUMBER THEN GOT$LINE = TRUE;
END;
ELSE IF F$CHAR = EOF$CHAR THEN GOT$RCD = FALSE; /* END OF FILE */
ELSE IF LN = LINE$NUMBER THEN CALL PR$BYTE( F$CHAR );
F$PTR = F$PTR + 1;
END;
CALL PR$CHAR( '>' ); CALL PR$NL;
/* SHOULD NOW HAVE EOF OR THE END OF THE REQUIRED LINE */
IF NOT GOT$LINE THEN DO;
/* COULDN'T READ THE SPECIFIED LINE */
CALL PR$STRING( .'CANNOT READ LINE $' );
CALL PR$NUMBER( LINE$NUMBER );
END;
/* CLOSE THE FILE */
IF NOT FL$CLOSE( FCB1 ) THEN DO;
CALL PR$STRING( .'UNABLE TO CLOSE THE FILE$' ); CALL PR$NL;
END;
END;
 
CALL EXIT;
 
EOF</syntaxhighlight>
 
=={{header|PowerShell}}==
{{works with|PowerShell|3.0}}
<syntaxhighlight lang="powershell">
$file = Get-Content c:\file.txt
if ($file.count -lt 7)
{Write-Warning "The file is too short!"}
else
{
$file | Where Readcount -eq 7 | set-variable -name Line7
}
</syntaxhighlight>
 
with open('xxx.txt') as f:
linelist = list(islice(f, 7, 8))
assert linelist != [], 'Not 7 lines in file'
line = linelist[0]</lang>
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">Structure lineLastRead
lineRead.i
line.s
Line 834 ⟶ 1,817:
MessageRequester("Error", "Couldn't open file " + filename + ".")
EndIf
EndIf </langsyntaxhighlight>
 
=={{header|Python}}==
 
Using only builtins (note that <code>enumerate</code> is zero-based):
 
<syntaxhighlight lang="python">with open('xxx.txt') as f:
for i, line in enumerate(f):
if i == 6:
break
else:
print('Not 7 lines in file')
line = None</syntaxhighlight>
 
Using the <code>islice</code> iterator function from the [https://docs.python.org/3/library/itertools.html#itertools.islice itertools] standard library module, which applies slicing to an iterator and thereby skips over the first six lines:
 
<syntaxhighlight lang="python">from itertools import islice
 
with open('xxx.txt') as f:
try:
line = next(islice(f, 6, 7))
except StopIteration:
print('Not 7 lines in file')</syntaxhighlight>
 
Similar to the Ruby implementation, this will read up to the first 7 lines, returning only the last. Note that the 'readlines' method reads the entire file contents into memory first as opposed to using the file iterator itself which is more performant for large files.
<syntaxhighlight lang="python">
print open('xxx.txt').readlines()[:7][-1]
</syntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">> seven <- scan('hw.txt', '', skip = 6, nlines = 1, sep = '\n') # too short
Read 0 items
> seven <- scan('Incoming/quotes.txt', '', skip = 6, nlines = 1, sep = '\n')
Read 1 item
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 850 ⟶ 1,860:
(define s1 (list-ref (file->lines "some-file") 6))
 
;; more efficient: read and discarediscard n-1 lines
(define s2
(call-with-input-file "some-file"
(λ(i) (for/last ([line (in-lines i)] [n 7]) line))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>say lines[6] // die "Short file";</syntaxhighlight>
Without an argument, the <tt>lines</tt> function reads filenames from the command line, or defaults to standard input. It then returns a lazy list, which we subscript to get the 7th element. Assuming this code is in a program called <tt>line7</tt>:
<pre>$ cal 2011 > cal.txt
$ line7 cal.txt
16 17 18 19 20 21 22 20 21 22 23 24 25 26 20 21 22 23 24 25 26
$</pre>
 
This works even on infinite files because lists are lazy:
<pre>$ yes | line7
y
$</pre>
 
=={{header|REBOL}}==
<syntaxhighlight lang="rebol">
x: pick read/lines request-file/only 7
either x [print x] [print "No seventh line"]
</syntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang="red">>> x: pick read/lines %file.txt 7
 
case [
x = none [print "File has less than seven lines"]
(length? x) = 0 [print "Line 7 is empty"]
(length? x) > 0 [print append "Line seven = " x]
]</syntaxhighlight>
 
=={{header|REXX}}==
===for newer REXXes===
<lang REXX>/*REXX program to read a specific line from a file. */
<syntaxhighlight lang="rexx">/*REXX program reads a specific line from a file (and displays the length and content).*/
parse arg fileId n . /*get the user args: fileid n */
parse arg FID n . /*obtain optional arguments from the CL*/
if fileID=='' then fileId='JUNK.TXT' /*assume the default: JUNK.TXT */
if nFID=='' | then nFID==7"," then FID= 'JUNK.TXT' /*not specified? Then /*assumeuse the default (n=7) .*/
Lif n==lines(fileid)'' | n=="," then n=7 /*first, see" " " " " if the" file exists. */
if L ==0 then do; say 'error, fileID not found:' fileId; exit; end
if n\==1 then call linein fileId,n-1 /*second, read previous rec. to N*/
L=lines(fileid) /* L = # lines left in the file.*/
q=linein(fileId,n) /*read the Nth line, store in Q.*/
qL=length(q) /*get the length of the record. */
select
when L==0 & qL==0 then say 'line' n "not found."
when L==1 & qL==0 then say 'line' n "has a zero length."
otherwise say 'file' fileId "record" n '=' q
end /*select*/
/*stick a fork in it, we're done.*/
/*┌────────────────────────────────────────────────────────────────────┐
│ ─── Normally, we could just use: ─── │
│ │
│ q=linein(fileId,n) /*read a specific record num. */ │
│ │
│── but LINEIN will just return a null when a record isn't found or│
│ when the fileID doesn't exist, or N is beyond the end-of-file.│
│ │
│── In the case of sparse files, the record may not exist (be null).│
└────────────────────────────────────────────────────────────────────┘*/</lang>
 
if lines(FID)==0 then call ser "wasn't found." /*see if the file exists (or not). */
=={{header|Ruby}}==
 
<lang ruby>def getNthLine(filename, n)
call linein FID, n-1 /*read the record previous to N. */
line=""
if lines(FID)==0 then call ser "doesn't contain" N 'lines.'
File.open(filename) do |f|
/* [↑] any more lines to read in file?*/
n.times do |nr|
 
line = f.gets
$=linein(FID) /*read the Nth record in the file. */
if line.nil?
 
puts "file #{filename} does not have #{n} lines, only #{nr}"
say 'File ' FID " line " N ' has a length of: ' length($)
break
say 'File ' FID " line " N 'contents: ' $ /*display the contents of the Nth line.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser: say; say '***error!*** File ' FID " " arg(1); say; exit 13</syntaxhighlight>
 
===for older REXXes===
Some older REXXes don't support a 2<sup>nd</sup> argument for the &nbsp; '''linein''' &nbsp; BIF, so here is an alternative:
<syntaxhighlight lang="rexx">/*REXX program reads a specific line from a file (and displays the length and content).*/
parse arg FID n . /*obtain optional arguments from the CL*/
if FID=='' | FID=="," then FID= 'JUNK.TXT' /*not specified? Then use the default.*/
if n=='' | n=="," then n=7 /* " " " " " " */
 
if lines(FID)==0 then call ser "wasn't found." /*see if the file exists (or not). */
 
do n-1
call linein FID /*read all the lines previous to N. */
end /*n-1*/
 
if lines(FID)==0 then call ser "doesn't contain" N 'lines.'
/* [↑] any more lines to read in file?*/
 
$=linein(FID) /*read the Nth record in the file. */
 
say 'File ' FID " line " N ' has a length of: ' length($)
say 'File ' FID " line " N 'contents: ' $ /*display the contents of the Nth line.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser: say; say '***error!*** File ' FID " " arg(1); say; exit 13</syntaxhighlight>
<br><br>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
fp = fopen("C:\Ring\ReadMe.txt","r")
n = 0
 
r = ""
while isstring(r)
while n < 8
r = fgetc(fp)
if r = char(10) n++ see nl
else see r ok
end
end
end
line
end
fclose(fp)
</syntaxhighlight>
 
=={{header|Ruby}}==
puts getNthLine("/etc/passwd", 7)</lang>
The each_line method returns an Enumerator, so no more than seven lines are read.
<syntaxhighlight lang="ruby"> seventh_line = open("/etc/passwd").each_line.take(7).last
</syntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">fileName$ = "f:\sample.txt"
requiredLine = 7
open fileName$ for input as #f
Line 911 ⟶ 1,972:
close #f
print a$
end</langsyntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Error;
use std::path::Path;
fn main() {
let path = Path::new("file.txt");
let line_num = 7usize;
let line = get_line_at(&path, line_num - 1);
println!("{}", line.unwrap());
}
fn get_line_at(path: &Path, line_num: usize) -> Result<String, Error> {
let file = File::open(path).expect("File not found or cannot be opened");
let content = BufReader::new(&file);
let mut lines = content.lines();
lines.nth(line_num).expect("No line found at that position")
}</syntaxhighlight>
 
Alternate implementation with argument parsing. First argument is the path to the file and is required. Second argument is the line number and is optional. By default the first line will be printed.
<syntaxhighlight lang="rust">use std::env;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::path::Path;
 
fn main() {
if env::args().len() <= 1 {
println!("At least a path to a file is needed: No file path given");
return;
} else {
let path = &env::args().nth(1).expect("could not parse the path");
let path = Path::new(&path);
let mut line_num = 1usize;
if let Some(arg) = env::args().nth(2) {
line_num = arg.parse::<usize>().expect("Parsing line number failed");
}
print_line_at(&path, line_num);
}
}
 
fn print_line_at(path: &Path, line_num: usize) {
if line_num < 1 {
panic!("Line number has to be > 0");
}
let line_num = line_num - 1;
let file = File::open(path).expect("File not found or cannot be opened");
let content = BufReader::new(&file);
let mut lines = content.lines();
let line = lines.nth(line_num).expect("No line found at given position");
println!("{}", line.expect("None line"));
}</syntaxhighlight>
 
=={{header|Scala}}==
===Discussion===
The code will throw a <tt>NoSuchElementException</tt> if the file doesn't have 7 lines.
 
<langsyntaxhighlight lang="scala">val lines = io.Source.fromFile("input.txt").getLines
val seventhLine = lines drop(6) next</langsyntaxhighlight>
===Imperative version===
 
Solving the task to the letter, imperative version:
 
<langsyntaxhighlight lang="scala">var lines: Iterator[String] = _
try {
lines = io.Source.fromFile("input.txt").getLines drop(6)
Line 933 ⟶ 2,050:
else seventhLine = lines next
}
if ("" == seventhLine) println("line is empty")</langsyntaxhighlight>
===Functional version (Recommanded)===
 
<syntaxhighlight lang="scala">val file = try Left(io.Source.fromFile("input.txt")) catch {
Functional version:
 
<lang scala>val file = try Left(io.Source.fromFile("input.txt")) catch {
case exc => Right(exc.getMessage)
}
val seventhLine = (for(f <- file.left;
line <- f.getLines.toStream.drop(6).headOption.toLeft("too few lines").left) yield
if (line == "") Right("line is empty") else Left(line)).joinLeft</langsyntaxhighlight>
 
=={{header|sed}}==
To print the seventh line:
<syntaxhighlight lang="sed">sed -n 7p</syntaxhighlight>
<lang sed>
To print an error message, if no such line:
sed -n 7p
<syntaxhighlight lang="sed">sed '7h;$!d;x;s/^$/Error: no such line/'</syntaxhighlight>
</lang>
That is we remember (h) the line, if any, in hold space. At the last line ($) we exchange (x) pattern space and hold space. If the hold space was empty, replace it by an error message. (Does not work with empty input, because there is no last line.)
To print error message if no such line
 
<lang sed>
sed -n '7{p;h;}; ${x;/^$/s/^/Error: no such line/p}'
</lang>
That is we remember (h) the line, if any, in hold space. At last line ($) we exchange (x) pattern space and hold space. If hold space was empty -- print error message.
=={{header|Seed7}}==
The function ''getLine'' skips lines with [http://seed7.sourceforge.net/libraries/file.htm#readln%28inout_file%29 readln]
and reads the requested line with [http://seed7.sourceforge.net/libraries/file.htm#getln%28inout_file%29 getln] afterwards:
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const func string: getLine (inout file: aFile, in var integer: lineNum) is func
Line 989 ⟶ 2,101:
end if;
end if;
end func;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
SenseTalk's chunk expressions and ability to treat a file directly as a container make this trivial. If the file has fewer than 7 lines, theLine will be empty.
<syntaxhighlight lang="sensetalk">put line 7 of file "example.txt" into theLine
</syntaxhighlight>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func getNthLine(filename, n) {
var file = File(filename)
file.open_r.each { |line|
Num($.) == n && return line
}
warn "file #{file} does not have #{n} lines, only #{$.}\n"
return nil
}
 
var line = getNthLine("/etc/passwd", 7)
say line if defined(line)</syntaxhighlight>
 
=={{header|Smalltalk}}==
<syntaxhighlight lang="smalltalk">
line := (StandardFileStream oldFileNamed: 'test.txt') contents lineNumber: 7.
</syntaxhighlight>
 
=={{header|SPL}}==
<syntaxhighlight lang="spl">lines = #.readlines("test.txt")
#.output("Seventh line of text:")
? #.size(lines,1)<7
#.output("is absent")
!
#.output(lines[7])
.</syntaxhighlight>
 
=={{header|Stata}}==
See '''[http://www.stata.com/help.cgi?use use]''' in Stata help, to load a dataset or a part of it.
 
<syntaxhighlight lang="stata">* Read rows 20 to 30 from somedata.dta
. use somedata in 20/30, clear
 
* Read rows for which the variable x is positive
. use somedata if x>0, clear</syntaxhighlight>
 
If there are not enough lines, an error message is print. It's possible to '''[http://www.stata.com/help.cgi?capture capture]''' the error and do something else:
 
<syntaxhighlight lang="stata">capture use somedata in 7, clear
if _rc {
display "Too few lines"
}</syntaxhighlight>
 
=={{header|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 ''n''th line is empty (as an empty line is still a valid line).
<langsyntaxhighlight lang="tcl">proc getNthLineFromFile {filename n} {
set f [open $filename]
while {[incr n -1] > 0} {
Line 1,005 ⟶ 2,165:
}
 
puts [getNthLineFromFile example.txt 7]</langsyntaxhighlight>
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 <code>seek</code> directly to the right location. This is rarely needed, but can occasionally be helpful.
 
=={{header|TorqueScript}}==
%file = new fileObject();
%file.openForRead("File/Path.txt");
$seventhLine = "";
while(!%file.isEOF())
{
%line++;
if(%line == 7)
{
$seventhLine = %file.readLine();
if($seventhLine $= "")
{
error("Line 7 of the file is blank!");
}
}
}
%file.close();
%file.delete();
if(%line < 7)
{
error("The file does not have seven lines!");
}
 
=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
file="lines.txt"
ERROR/STOP OPEN (file,READ,-std-)
line2fetch=7</syntaxhighlight>
 
=={{header|TXR}}==
===From the top===
Variable "line" matches and takes eighth line of input:
<langsyntaxhighlight lang="txr">@(skip nil 7)
@line</langsyntaxhighlight>
 
===From the bottom===
Take the third line from the bottom of the file, if it exists.
<langsyntaxhighlight lang="txr">@(skip)
@line
@(skip 1 2)
@(eof)</langsyntaxhighlight>
How this works is that the first <code>skip</code> will skip enough lines until the rest of the query successfully matches the input. The rest of the query matches a line, then skips two lines, and matches on EOF. So <code>@line</code> can only match at one location: three lines up from the end of the file. If the file doesn't have at least three lines, the query fails.
 
=={{header|TUSCRIPTUNIX Shell}}==
{{trans|Tcl}}
<lang tuscript>$$ MODE TUSCRIPT
{{works with|bash}}
file="lines.txt"
<syntaxhighlight lang="bash">get_nth_line() {
ERROR/STOP OPEN (file,READ,-std-)
local file=$1 n=$2 line
line2fetch=7
while ((n-- > 0)); do
if ! IFS= read -r line; then
echo "No such line $2 in $file"
return 1
fi
done < "$file"
echo "$line"
}
 
get_nth_line filename 7</syntaxhighlight>
--> solution 1
ACCESS file: READ/RECORDS/UTF8 $file s,line
LOOP n=1,99
READ/NEXT/EXIT file
IF (n==line2fetch) PRINT line
ENDLOOP
ENDACCESS file
 
You can also use standard tools instead of built-ins:.
--> solution 2
 
line1to7=FILE (file,#line2fetch)
<syntaxhighlight lang="bash">awk NR==7 filename
line=SELECT (line1to7,#line2fetch)
sed -n 7p filename
PRINT line</lang>
head -n 7 filename | tail -n 1</syntaxhighlight>
Output:
 
=={{header|Ursa}}==
<syntaxhighlight lang="ursa">decl string<> lines
decl file f
f.open "filename.txt"
set lines (f.readlines)
f.close
 
if (< (size lines) 7)
out "the file has less than seven lines" endl console
stop
end if
 
out "the seventh line in the file is:" endl endl console
out lines<6> endl console</syntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(filepath,1)
arrLines = Split(objFile.ReadAll,vbCrLf)
If UBound(arrLines) >= n-1 Then
If arrLines(n-1) <> "" Then
read_line = arrLines(n-1)
Else
read_line = "Line " & n & " is null."
End If
Else
read_line = "Line " & n & " does not exist."
End If
objFile.Close
Set objFSO = Nothing
End Function
 
WScript.Echo read_line("c:\temp\input.txt",7)
</syntaxhighlight>
 
{{In}}
<pre>
1st
line7
22d
line7
3rd
4th
5th
6th
7th
8th
</pre>
 
{{Out}}
<pre>7th</pre>
 
=={{header|Vedit macro language}}==
This example reads the 7th line (including newline character(s)) into text register 10.
 
<langsyntaxhighlight lang="vedit">File_Open("example.txt", BROWSE)
Goto_Line(7)
if (Cur_Line < 7) {
Line 1,059 ⟶ 2,303:
Reg_Copy(10, 1)
}
Buf_Close(NOMSG) </langsyntaxhighlight>
 
If the file does not exist, the buffer will be empty and you get "File contains too few lines" error.
Line 1,065 ⟶ 2,309:
If the line is too long (more than about 230,000 characters), Vedit displays error message "Block too large for text registers, try clipboard").
This error could be avoided by reading the line to clipboard (which has larger size limit) or by copying the line to another edit buffer using a tmp file (in which case there is no size limit).
 
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="wren">import "io" for File
 
var lines = File.read("input.txt").replace("\r", "").split("\n")
if (lines.count < 7) {
System.print("There are only %(lines.count) lines in the file")
} else {
var line7 = lines[6].trim()
if (line7 == "") {
System.print("The seventh line is empty")
} else {
System.print("The seventh line is : %(line7)")
}
}
 
/* Note that 'input.txt' contains the eight lines:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
*/</syntaxhighlight>
 
{{out}}
<pre>
The seventh line is : Line 7
</pre>
 
=={{header|XPL0}}==
Line 1,070 ⟶ 2,346:
Usage: readline <filename.ext
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
def MaxLen = 82; \maximum length of line that can be stored (incl CR+LF)
 
Line 1,095 ⟶ 2,371:
 
char LineN(MaxLen);
if ReadLine(7, LineN) then Text(0, LineN)</langsyntaxhighlight>
 
=={{header|zkl}}==
Many zkl sequence objects contain a readln method, some contain a seek (or equivalent) method. However, File only has readln. If, for some, reason, the nth line can't be read, an exception is thrown.
<syntaxhighlight lang="zkl">reg line; do(7){line=File.stdin.readln()} println(">>>",line);</syntaxhighlight>
Or, suck in lines and take the last one:
<syntaxhighlight lang="zkl">lines:=File.stdin.readln(7); println(">>>",line[-1]);</syntaxhighlight>
 
 
[[Category:File handling]]
9,476

edits