Read a specific line from a file: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 18: Line 18:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>V f = File(‘input.txt’)
<syntaxhighlight lang="11l">V f = File(‘input.txt’)
V line = 3
V line = 3


L 0 .< line - 1
L 0 .< line - 1
f.read_line()
f.read_line()
print(f.read_line())</lang>
print(f.read_line())</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
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.
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.
<lang Action!>BYTE FUNC ReadLine(CHAR ARRAY fname CARD index CHAR ARRAY result)
<syntaxhighlight lang="action!">BYTE FUNC ReadLine(CHAR ARRAY fname CARD index CHAR ARRAY result)
CHAR ARRAY line(255)
CHAR ARRAY line(255)
CARD curr
CARD curr
Line 72: Line 72:
Test(fname,24)
Test(fname,24)
Test(fname,50)
Test(fname,50)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{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]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Read_a_specific_line_from_a_file.png Screenshot from Atari 8-bit computer]
Line 91: Line 91:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;


procedure Rosetta_Read is
procedure Rosetta_Read is
Line 119: Line 119:
Put_Line ("Line 7 is too long to load.");
Put_Line ("Line 7 is too long to load.");
Close (File);
Close (File);
end Rosetta_Read;</lang>
end Rosetta_Read;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>void
<syntaxhighlight lang="aime">void
read_line(text &line, text path, integer n)
read_line(text &line, text path, integer n)
{
{
Line 147: Line 147:


0;
0;
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<lang algol68># reads the line with number "number" (counting from 1) #
<syntaxhighlight lang="algol68"># reads the line with number "number" (counting from 1) #
# from the file named "file name" and returns the text of the #
# from the file named "file name" and returns the text of the #
# in "line". If an error occurs, the result is FALSE and a #
# in "line". If an error occurs, the result is FALSE and a #
Line 220: Line 220:
print( ( "unable to read line: """ + err + """" ) )
print( ( "unable to read line: """ + err + """" ) )
FI
FI
)</lang>
)</syntaxhighlight>
=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
#include <hopper.h>
#define MAX_LINE_SIZE 1000
#define MAX_LINE_SIZE 1000
Line 238: Line 238:
fclose(fd)
fclose(fd)
exit(0)
exit(0)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 246: Line 246:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>FileReadLine, OutputVar, filename.txt, 7
<syntaxhighlight lang="autohotkey">FileReadLine, OutputVar, filename.txt, 7
if ErrorLevel
if ErrorLevel
MsgBox, There was an error reading the 7th line of the file</lang>
MsgBox, There was an error reading the 7th line of the file</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>#!/usr/bin/awk -f
<syntaxhighlight lang="awk">#!/usr/bin/awk -f
#usage: readnthline.awk -v lineno=6 filename
#usage: readnthline.awk -v lineno=6 filename


Line 263: Line 263:
print storedline
print storedline
}
}
</syntaxhighlight>
</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==
==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang basic256>f = freefile
<syntaxhighlight lang="basic256">f = freefile
filename$ = "input.txt"
filename$ = "input.txt"
open f, filename$
open f, filename$
Line 283: Line 283:
if cont < lineapedida then print "There are only "; cont; " lines in the file"
if cont < lineapedida then print "There are only "; cont; " lines in the file"
close f
close f
end</lang>
end</syntaxhighlight>


==={{header|OxygenBasic}}===
==={{header|OxygenBasic}}===
library OOP
library OOP
<lang>
<syntaxhighlight lang="text">
uses stringutil
uses stringutil
new Textarray t
new Textarray t
Line 294: Line 294:
' print t.lineCount
' print t.lineCount
del t
del t
</syntaxhighlight>
</lang>


==={{header|QBasic}}===
==={{header|QBasic}}===
{{works with|QBasic}}
{{works with|QBasic}}
<lang QBasic>f = FREEFILE
<syntaxhighlight lang="qbasic">f = FREEFILE
OPEN "input.txt" FOR INPUT AS #f
OPEN "input.txt" FOR INPUT AS #f


Line 312: Line 312:
LOOP
LOOP
IF cont < lineapedida THEN PRINT "There are only "; cont; " lines in the file"
IF cont < lineapedida THEN PRINT "There are only "; cont; " lines in the file"
CLOSE #1</lang>
CLOSE #1</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<lang qbasic>LET filename$ = "input.txt"
<syntaxhighlight lang="qbasic">LET filename$ = "input.txt"
OPEN #1: NAME filename$, ORG TEXT, ACCESS INPUT, CREATE OLD
OPEN #1: NAME filename$, ORG TEXT, ACCESS INPUT, CREATE OLD


Line 330: Line 330:
IF cont < lineapedida THEN PRINT "There are only "; cont; " lines in the file"
IF cont < lineapedida THEN PRINT "There are only "; cont; " lines in the file"
CLOSE #1
CLOSE #1
END</lang>
END</syntaxhighlight>


==={{header|Yabasic}}===
==={{header|Yabasic}}===
<lang yabasic>filename$ = "input.txt"
<syntaxhighlight lang="yabasic">filename$ = "input.txt"
open filename$ for reading as #1
open filename$ for reading as #1


Line 348: Line 348:
if cont < lineapedida print "There are only ", cont, " lines in the file"
if cont < lineapedida print "There are only ", cont, " lines in the file"
close #1
close #1
end</lang>
end</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>
<syntaxhighlight lang="dos">
@echo off
@echo off


Line 361: Line 361:
echo Line 7 is: %line7%
echo Line 7 is: %line7%
pause>nul
pause>nul
</syntaxhighlight>
</lang>
{{in}}
{{in}}
<pre>
<pre>
Line 381: Line 381:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> filepath$ = @lib$ + "..\licence.txt"
<syntaxhighlight lang="bbcbasic"> filepath$ = @lib$ + "..\licence.txt"
requiredline% = 7
requiredline% = 7
Line 393: Line 393:
IF ASCtext$=10 text$ = MID$(text$,2)
IF ASCtext$=10 text$ = MID$(text$,2)
PRINT text$</lang>
PRINT text$</syntaxhighlight>


=={{header|C}}==
=={{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.
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.
<lang c>#include <unistd.h>
<syntaxhighlight lang="c">#include <unistd.h>
#include <sys/types.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/mman.h>
Line 462: Line 462:


return ret;
return ret;
}</lang>
}</syntaxhighlight>


===Alternate Version===
===Alternate Version===
Line 468: Line 468:
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.
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.


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 569: Line 569:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


=={{header|C sharp}}==
=={{header|C sharp}}==


<lang C sharp>using System;
<syntaxhighlight lang="c sharp">using System;
using System.IO;
using System.IO;


Line 616: Line 616:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <fstream>
#include <fstream>
#include <iostream>
#include <iostream>
Line 652: Line 652:
return 1 ;
return 1 ;
}
}
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(defn read-nth-line
<syntaxhighlight lang="clojure">(defn read-nth-line
"Read line-number from the given text file. The first line has the number 1."
"Read line-number from the given text file. The first line has the number 1."
[file line-number]
[file line-number]
(with-open [rdr (clojure.java.io/reader file)]
(with-open [rdr (clojure.java.io/reader file)]
(nth (line-seq rdr) (dec line-number))))</lang>
(nth (line-seq rdr) (dec line-number))))</syntaxhighlight>


{{out}}
{{out}}
Line 667: Line 667:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


<lang lisp>(defun read-nth-line (file n &aux (line-number 0))
<syntaxhighlight 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"
"Read the nth line from a text file. The first line has the number 1"
(assert (> n 0) (n))
(assert (> n 0) (n))
Line 678: Line 678:
if (and line (= line-number n))
if (and line (= line-number n))
do (return line))))
do (return line))))
</syntaxhighlight>
</lang>


Example call:
Example call:
Line 686: Line 686:
=={{header|D}}==
=={{header|D}}==
simply
simply
<syntaxhighlight lang="d">
<lang d>
void main() {
void main() {
import std.stdio, std.file, std.string;
import std.stdio, std.file, std.string;
Line 693: Line 693:
writeln((file_lines.length > 6) ? file_lines[6] : "line not found");
writeln((file_lines.length > 6) ? file_lines[6] : "line not found");
}
}
</syntaxhighlight>
</lang>


or, line by line
or, line by line
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


void main() {
void main() {
Line 717: Line 717:
writefln("the file only contains %d lines", countLines);
writefln("the file only contains %d lines", countLines);
}
}
}</lang>
}</syntaxhighlight>
<pre>
<pre>
line 7: foreach (char[] line; f.byLine()) {</pre>
line 7: foreach (char[] line; f.byLine()) {</pre>
Line 723: Line 723:
{{libheader| System.SysUtils}}
{{libheader| System.SysUtils}}
{{Trans|Pascal}}
{{Trans|Pascal}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Read_a_specific_line_from_a_file;
program Read_a_specific_line_from_a_file;


Line 761: Line 761:
Writeln(ReadLine(7, 'test'));
Writeln(ReadLine(7, 'test'));
Readln;
Readln;
end.</lang>
end.</syntaxhighlight>


=={{header|Elixir}}==
=={{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.
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">
<lang Elixir>
defmodule LineReader do
defmodule LineReader do
def get_line(filename, line) do
def get_line(filename, line) do
Line 777: Line 777:
defp print_line(_), do: {:error, "Invalid Line"}
defp print_line(_), do: {:error, "Invalid Line"}
end
end
</syntaxhighlight>
</lang>


=={{header|Erlang}}==
=={{header|Erlang}}==
Using function into_list/1 from [[Read_a_file_line_by_line]].
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?
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 ).
-module( read_a_specific_line ).


Line 813: Line 813:
line_nr_error( function_clause ) -> too_few_lines_in_file;
line_nr_error( function_clause ) -> too_few_lines_in_file;
line_nr_error( Error ) -> Error.
line_nr_error( Error ) -> Error.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 830: Line 830:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System
open System.IO
open System.IO


Line 844: Line 844:
// if not not enough lines available
// if not not enough lines available
Console.WriteLine(line)
Console.WriteLine(line)
0</lang>
0</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: continuations fry io io.encodings.utf8 io.files kernel
<syntaxhighlight lang="factor">USING: continuations fry io io.encodings.utf8 io.files kernel
math ;
math ;
IN: rosetta-code.nth-line
IN: rosetta-code.nth-line
Line 861: Line 861:
print ;
print ;


MAIN: nth-line-demo</lang>
MAIN: nth-line-demo</syntaxhighlight>


=={{header|Fortran}}==
=={{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.
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.<lang Fortran> MODULE SAMPLER !To sample a record from a file. SAM00100
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
CONTAINS SAM00200
CHARACTER*20 FUNCTION GETREC(N,F,IS) !Returns a status. SAM00300
CHARACTER*20 FUNCTION GETREC(N,F,IS) !Returns a status. SAM00300
Line 933: Line 933:
666 WRITE (MSG,*) "Can't get the record!" POK02700
666 WRITE (MSG,*) "Can't get the record!" POK02700
END !That was easy. POK02800
END !That was easy. POK02800
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 953: Line 953:
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.
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 <lang Fortran>READ (F'7) STUFF(1:80)</lang> - 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.
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: <lang Fortran> READ (F,REC = 7,ERR = 666, IOSTAT = IOSTAT) STUFF(1:80)
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
666 IF (IOSTAT.NE.0) THEN
WRITE (MSG,*) "Can't get the record: code",IOSTAT
WRITE (MSG,*) "Can't get the record: code",IOSTAT
ELSE
ELSE
WRITE (MSG,1) "Record",STUFF(1:80)
WRITE (MSG,1) "Record",STUFF(1:80)
END IF</lang>
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>
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}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Open "input.txt" For Input As #1
Open "input.txt" For Input As #1
Line 989: Line 989:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep </lang>
Sleep </syntaxhighlight>


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>nthLine[filename, lineNum] :=
<syntaxhighlight lang="frink">nthLine[filename, lineNum] :=
{
{
line = nth[lines[filenameToURL[filename]], lineNum-1]
line = nth[lines[filenameToURL[filename]], lineNum-1]
Line 1,002: Line 1,002:
return undef
return undef
}
}
}</lang>
}</syntaxhighlight>


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
Uses FB's openpanel command that opens a dialog window and allows the user to select the file to read.
Uses FB's openpanel command that opens a dialog window and allows the user to select the file to read.
<lang futurebasic>window 1
<syntaxhighlight lang="futurebasic">window 1


long i = 1
long i = 1
Line 1,031: Line 1,031:
end if
end if


HandleEvents</lang>
HandleEvents</syntaxhighlight>


Input text file:
Input text file:
Line 1,052: Line 1,052:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,102: Line 1,102:
}
}
return line, nil
return line, nil
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def line = null
<syntaxhighlight lang="groovy">def line = null
new File("lines.txt").eachLine { currentLine, lineNumber ->
new File("lines.txt").eachLine { currentLine, lineNumber ->
if (lineNumber == 7) {
if (lineNumber == 7) {
Line 1,111: Line 1,111:
}
}
}
}
println "Line 7 = $line"</lang>
println "Line 7 = $line"</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==


<lang Haskell>main :: IO ()
<syntaxhighlight lang="haskell">main :: IO ()
main = do contents <- readFile filename
main = do contents <- readFile filename
case drop 6 $ lines contents of
case drop 6 $ lines contents of
[] -> error "File has less than seven lines"
[] -> error "File has less than seven lines"
l:_ -> putStrLn l
l:_ -> putStrLn l
where filename = "testfile"</lang>
where filename = "testfile"</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 1,127: Line 1,127:
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.
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.


<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
write(readline("foo.bar.txt",7)|"failed")
write(readline("foo.bar.txt",7)|"failed")
end
end
Line 1,136: Line 1,136:
close(f)
close(f)
if i = 0 then return line
if i = 0 then return line
end</lang>
end</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang j>readLine=: 4 :0
<syntaxhighlight lang="j">readLine=: 4 :0
(x-1) {:: <;.2 ] 1!:1 boxxopen y
(x-1) {:: <;.2 ] 1!:1 boxxopen y
)</lang>
)</syntaxhighlight>


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


<lang j> 7 readLine 'cal.txt'
<syntaxhighlight 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>
9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19</syntaxhighlight>


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.
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'''
'''Tacit alternative'''
<lang j>require 'files' NB. required for versions before J701
<syntaxhighlight lang="j">require 'files' NB. required for versions before J701
readLineT=: <:@[ {:: 'b'&freads@]</lang>
readLineT=: <:@[ {:: 'b'&freads@]</syntaxhighlight>
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.
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 1,159: Line 1,159:
<tt>example: java -cp . LineNbr7 LineNbr7.java</tt><br>
<tt>example: java -cp . LineNbr7 LineNbr7.java</tt><br>
<tt>output : line 7: public static void main(String[] args) throws Exception {;</tt>
<tt>output : line 7: public static void main(String[] args) throws Exception {;</tt>
<lang java>package linenbr7;
<syntaxhighlight lang="java">package linenbr7;


import java.io.*;
import java.io.*;
Line 1,191: Line 1,191:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Line 1,200: Line 1,200:
* "foreach" - a control structure for iterating over a stream
* "foreach" - a control structure for iterating over a stream
* "break" - for breaking out of a loop
* "break" - for breaking out of a loop
<lang jq># Input - a line number to read, counting from 1
<syntaxhighlight lang="jq"># Input - a line number to read, counting from 1
# Output - a stream with 0 or 1 items
# Output - a stream with 0 or 1 items
def read_line:
def read_line:
Line 1,206: Line 1,206:
| label $top
| label $top
| foreach inputs as $line
| foreach inputs as $line
(0; .+1; if . == $in then $line, break $top else empty end) ;</lang>
(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
'''Example:''' Read line number $line (to be provided on the command line), counting from 1
<lang jq>$line | tonumber
<syntaxhighlight lang="jq">$line | tonumber
| if . > 0 then read_line
| if . > 0 then read_line
else "$line (\(.)) should be a non-negative integer"
else "$line (\(.)) should be a non-negative integer"
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<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
<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</lang>
9</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
The short following snippet of code actually stores all the lines from the file in an array and displays 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.
The short following snippet of code actually stores all the lines from the file in an array and displays 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.
<lang Julia>open(readlines, "path/to/file")[7]</lang>
<syntaxhighlight lang="julia">open(readlines, "path/to/file")[7]</syntaxhighlight>
The next function reads n lines in the file and displays the last read if possible, or returns 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.
The next function reads n lines in the file and displays the last read if possible, or returns 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.
<lang Julia>function read_nth_lines(stream, num)
<syntaxhighlight lang="julia">function read_nth_lines(stream, num)
for i = 1:num-1
for i = 1:num-1
readline(stream)
readline(stream)
Line 1,226: Line 1,226:
result = readline(stream)
result = readline(stream)
print(result != "" ? result : "No such line.")
print(result != "" ? result : "No such line.")
end</lang>
end</syntaxhighlight>
{{Out}}
{{Out}}
<pre>julia> open(line -> read_nth_lines(line, 7), "path/to/file")
<pre>julia> open(line -> read_nth_lines(line, 7), "path/to/file")
Line 1,232: Line 1,232:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


import java.io.File
import java.io.File
Line 1,263: Line 1,263:
Line 7
Line 7
Line 8
Line 8
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 1,271: Line 1,271:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(f) = file('unixdict.txt')
<syntaxhighlight lang="lasso">local(f) = file('unixdict.txt')
handle => { #f->close }
handle => { #f->close }
local(this_line = string,line = 0)
local(this_line = string,line = 0)
Line 1,280: Line 1,280:
}
}
#this_line // 6th, which is the 7th line in the file
#this_line // 6th, which is the 7th line in the file
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{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.
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.
<lang lb>fileName$ ="F:\sample.txt"
<syntaxhighlight lang="lb">fileName$ ="F:\sample.txt"
requiredLine =7
requiredLine =7


Line 1,294: Line 1,294:
if line7$ =chr$( 13) +chr$( 10) or line7$ ="" then notice "Empty line! ( or file has fewer lines)."
if line7$ =chr$( 13) +chr$( 10) or line7$ ="" then notice "Empty line! ( or file has fewer lines)."


print line7$</lang>
print line7$</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function fileLine (lineNum, fileName)
<syntaxhighlight lang="lua">function fileLine (lineNum, fileName)
local count = 0
local count = 0
for line in io.lines(fileName) do
for line in io.lines(fileName) do
Line 1,306: Line 1,306:
end
end


print(fileLine(7, "test.txt"))</lang>
print(fileLine(7, "test.txt"))</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>path := "file.txt":
<syntaxhighlight lang="maple">path := "file.txt":
specificLine := proc(path, num)
specificLine := proc(path, num)
local i, input:
local i, input:
Line 1,318: Line 1,318:
if i = num+1 then printf("Line %d, %s", num, input):
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:
elif i <= num then printf ("Line number %d is not reached",num): end if:
end proc:</lang>
end proc:</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica> If[# != EndOfFile , Print[#]]& @ ReadList["file", String, 7]</lang>
<syntaxhighlight lang="mathematica"> If[# != EndOfFile , Print[#]]& @ ReadList["file", String, 7]</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==


<syntaxhighlight lang="matlab">
<lang Matlab>
eln = 7; % extract line number 7
eln = 7; % extract line number 7
line = '';
line = '';
Line 1,344: Line 1,344:
end;
end;
printf('line %i: %s\n',eln,line);
printf('line %i: %s\n',eln,line);
</lang>
</syntaxhighlight>
<nowiki>Insert non-formatted text here</nowiki>
<nowiki>Insert non-formatted text here</nowiki>


=={{header|MoonScript}}==
=={{header|MoonScript}}==
{{trans|Lua}}
{{trans|Lua}}
<lang MoonScript>iter = io.lines 'test.txt'
<syntaxhighlight lang="moonscript">iter = io.lines 'test.txt'
for i=0, 5
for i=0, 5
error 'Not 7 lines in file' if not iter!
error 'Not 7 lines in file' if not iter!


print iter!</lang>
print iter!</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>def getline(fname, linenum)
<syntaxhighlight lang="nanoquery">def getline(fname, linenum)
contents = null
contents = null
try
try
Line 1,368: Line 1,368:
end
end
end
end
end</lang>
end</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 1,423: Line 1,423:
method isFalse() public static returns boolean
method isFalse() public static returns boolean
return \(1 == 1)
return \(1 == 1)
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==


<lang nim>import strformat
<syntaxhighlight lang="nim">import strformat


proc readLine(f: File; num: Positive): string =
proc readLine(f: File; num: Positive): string =
Line 1,439: Line 1,439:
echo f.readLine(7)
echo f.readLine(7)
f.close()
f.close()
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
Line 1,445: Line 1,445:
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:
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:


<lang ocaml>let input_line_opt ic =
<syntaxhighlight lang="ocaml">let input_line_opt ic =
try Some (input_line ic)
try Some (input_line ic)
with End_of_file -> None
with End_of_file -> None
Line 1,465: Line 1,465:


let () =
let () =
print_endline (nth_line 7 Sys.argv.(1))</lang>
print_endline (nth_line 7 Sys.argv.(1))</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Line 1,472: Line 1,472:
=={{header|Pascal}}==
=={{header|Pascal}}==
{{works with|Free_Pascal}}
{{works with|Free_Pascal}}
<lang pascal>Program FileTruncate;
<syntaxhighlight lang="pascal">Program FileTruncate;


uses
uses
Line 1,509: Line 1,509:
Close(myfile);
Close(myfile);
writeln(line);
writeln(line);
end.</lang>
end.</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,516: Line 1,516:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>#!/usr/bin/perl -s
<syntaxhighlight lang="perl">#!/usr/bin/perl -s
# invoke as <scriptname> -n=7 [input]
# invoke as <scriptname> -n=7 [input]
while (<>) { $. == $n and print, exit }
while (<>) { $. == $n and print, exit }
die "file too short\n";</lang>
die "file too short\n";</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
No specific mechanism, but simple enough. If the file is suitably small:
No specific mechanism, but simple enough. If the file is suitably small:
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<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>
<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>
<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>
<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>
Line 1,530: Line 1,530:
<span style="color: #0000FF;">?</span><span style="color: #008000;">"no line 7"</span>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
For bigger files:
For bigger files:
<!--<lang Phix>-->
<!--<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: #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: #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>
Line 1,539: Line 1,539:
<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: #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>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>include ..\Utilitys.pmt
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt


argument 1 get "r" fopen var f drop
argument 1 get "r" fopen var f drop
Line 1,549: Line 1,549:
f fgets number? if f fclose exitfor else nip nip endif
f fgets number? if f fclose exitfor else nip nip endif
endfor
endfor
print /# show -1 if past eof #/</lang>
print /# show -1 if past eof #/</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
Line 1,568: Line 1,568:
if (!$fp) die("Input file not found!");
if (!$fp) die("Input file not found!");
echo fileLine(7, $fp);
echo fileLine(7, $fp);
?></lang>
?></syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(in "file.txt"
<syntaxhighlight lang="picolisp">(in "file.txt"
(do 6 (line))
(do 6 (line))
(or (line) (quit "No 7 lines")) )</lang>
(or (line) (quit "No 7 lines")) )</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>
<syntaxhighlight lang="pli">
declare text character (1000) varying, line_no fixed;
declare text character (1000) varying, line_no fixed;


Line 1,589: Line 1,589:
put skip list (text);
put skip list (text);
next: ;
next: ;
</syntaxhighlight>
</lang>


=={{header|PL/M}}==
=={{header|PL/M}}==
This is written for the original 8080 PL/M compiler and can be run under CP/M or an emulator or clone.
This is written for the original 8080 PL/M compiler and can be run under CP/M or an emulator or clone.
<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.
<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 pli>100H: /* READ A SPECIFIC LINE FROM A FILE */
<syntaxhighlight lang="pli">100H: /* READ A SPECIFIC LINE FROM A FILE */


DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';
Line 1,726: Line 1,726:
CALL EXIT;
CALL EXIT;


EOF</lang>
EOF</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{works with|PowerShell|3.0}}
{{works with|PowerShell|3.0}}
<syntaxhighlight lang="powershell">
<lang Powershell>
$file = Get-Content c:\file.txt
$file = Get-Content c:\file.txt
if ($file.count -lt 7)
if ($file.count -lt 7)
Line 1,738: Line 1,738:
$file | Where Readcount -eq 7 | set-variable -name Line7
$file | Where Readcount -eq 7 | set-variable -name Line7
}
}
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang purebasic>Structure lineLastRead
<syntaxhighlight lang="purebasic">Structure lineLastRead
lineRead.i
lineRead.i
line.s
line.s
Line 1,772: Line 1,772:
MessageRequester("Error", "Couldn't open file " + filename + ".")
MessageRequester("Error", "Couldn't open file " + filename + ".")
EndIf
EndIf
EndIf </lang>
EndIf </syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Line 1,778: Line 1,778:
Using only builtins (note that <code>enumerate</code> is zero-based):
Using only builtins (note that <code>enumerate</code> is zero-based):


<lang python>with open('xxx.txt') as f:
<syntaxhighlight lang="python">with open('xxx.txt') as f:
for i, line in enumerate(f):
for i, line in enumerate(f):
if i == 6:
if i == 6:
Line 1,784: Line 1,784:
else:
else:
print('Not 7 lines in file')
print('Not 7 lines in file')
line = None</lang>
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:
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:


<lang python>from itertools import islice
<syntaxhighlight lang="python">from itertools import islice


with open('xxx.txt') as f:
with open('xxx.txt') as f:
Line 1,794: Line 1,794:
line = next(islice(f, 6, 7))
line = next(islice(f, 6, 7))
except StopIteration:
except StopIteration:
print('Not 7 lines in file')</lang>
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.
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.
<lang python>
<syntaxhighlight lang="python">
print open('xxx.txt').readlines()[:7][-1]
print open('xxx.txt').readlines()[:7][-1]
</syntaxhighlight>
</lang>


=={{header|R}}==
=={{header|R}}==
<lang R>> seven <- scan('hw.txt', '', skip = 6, nlines = 1, sep = '\n') # too short
<syntaxhighlight lang="r">> seven <- scan('hw.txt', '', skip = 6, nlines = 1, sep = '\n') # too short
Read 0 items
Read 0 items
> seven <- scan('Incoming/quotes.txt', '', skip = 6, nlines = 1, sep = '\n')
> seven <- scan('Incoming/quotes.txt', '', skip = 6, nlines = 1, sep = '\n')
Read 1 item
Read 1 item
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 1,819: Line 1,819:
(call-with-input-file "some-file"
(call-with-input-file "some-file"
(λ(i) (for/last ([line (in-lines i)] [n 7]) line))))
(λ(i) (for/last ([line (in-lines i)] [n 7]) line))))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>say lines[6] // die "Short file";</lang>
<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>:
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
<pre>$ cal 2011 > cal.txt
Line 1,836: Line 1,836:


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang rebol>
<syntaxhighlight lang="rebol">
x: pick read/lines request-file/only 7
x: pick read/lines request-file/only 7
either x [print x] [print "No seventh line"]
either x [print x] [print "No seventh line"]
</syntaxhighlight>
</lang>


=={{header|Red}}==
=={{header|Red}}==
<lang Red>>> x: pick read/lines %file.txt 7
<syntaxhighlight lang="red">>> x: pick read/lines %file.txt 7


case [
case [
Line 1,848: Line 1,848:
(length? x) = 0 [print "Line 7 is empty"]
(length? x) = 0 [print "Line 7 is empty"]
(length? x) > 0 [print append "Line seven = " x]
(length? x) > 0 [print append "Line seven = " x]
]</lang>
]</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===for newer REXXes===
===for newer REXXes===
<lang REXX>/*REXX program reads a specific line from a file (and displays the length and content).*/
<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*/
parse arg FID n . /*obtain optional arguments from the CL*/
if FID=='' | FID=="," then FID= 'JUNK.TXT' /*not specified? Then use the default.*/
if FID=='' | FID=="," then FID= 'JUNK.TXT' /*not specified? Then use the default.*/
Line 1,869: Line 1,869:
exit /*stick a fork in it, we're all done. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser: say; say '***error!*** File ' FID " " arg(1); say; exit 13</lang>
ser: say; say '***error!*** File ' FID " " arg(1); say; exit 13</syntaxhighlight>


===for older REXXes===
===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:
Some older REXXes don't support a 2<sup>nd</sup> argument for the &nbsp; '''linein''' &nbsp; BIF, so here is an alternative:
<lang REXX>/*REXX program reads a specific line from a file (and displays the length and content).*/
<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*/
parse arg FID n . /*obtain optional arguments from the CL*/
if FID=='' | FID=="," then FID= 'JUNK.TXT' /*not specified? Then use the default.*/
if FID=='' | FID=="," then FID= 'JUNK.TXT' /*not specified? Then use the default.*/
Line 1,893: Line 1,893:
exit /*stick a fork in it, we're all done. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser: say; say '***error!*** File ' FID " " arg(1); say; exit 13</lang>
ser: say; say '***error!*** File ' FID " " arg(1); say; exit 13</syntaxhighlight>
<br><br>
<br><br>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
fp = fopen("C:\Ring\ReadMe.txt","r")
fp = fopen("C:\Ring\ReadMe.txt","r")
n = 0
n = 0
Line 1,910: Line 1,910:
end
end
fclose(fp)
fclose(fp)
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
The each_line method returns an Enumerator, so no more than seven lines are read.
The each_line method returns an Enumerator, so no more than seven lines are read.
<lang ruby> seventh_line = open("/etc/passwd").each_line.take(7).last
<syntaxhighlight lang="ruby"> seventh_line = open("/etc/passwd").each_line.take(7).last
</syntaxhighlight>
</lang>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>fileName$ = "f:\sample.txt"
<syntaxhighlight lang="runbasic">fileName$ = "f:\sample.txt"
requiredLine = 7
requiredLine = 7
open fileName$ for input as #f
open fileName$ for input as #f
Line 1,927: Line 1,927:
close #f
close #f
print a$
print a$
end</lang>
end</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::fs::File;
<syntaxhighlight lang="rust">use std::fs::File;
use std::io::BufRead;
use std::io::BufRead;
use std::io::BufReader;
use std::io::BufReader;
Line 1,948: Line 1,948:
let mut lines = content.lines();
let mut lines = content.lines();
lines.nth(line_num).expect("No line found at that position")
lines.nth(line_num).expect("No line found at that position")
}</lang>
}</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.
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.
<lang rust>use std::env;
<syntaxhighlight lang="rust">use std::env;
use std::fs::File;
use std::fs::File;
use std::io::BufRead;
use std::io::BufRead;
Line 1,982: Line 1,982:
let line = lines.nth(line_num).expect("No line found at given position");
let line = lines.nth(line_num).expect("No line found at given position");
println!("{}", line.expect("None line"));
println!("{}", line.expect("None line"));
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
Line 1,988: Line 1,988:
The code will throw a <tt>NoSuchElementException</tt> if the file doesn't have 7 lines.
The code will throw a <tt>NoSuchElementException</tt> if the file doesn't have 7 lines.


<lang scala>val lines = io.Source.fromFile("input.txt").getLines
<syntaxhighlight lang="scala">val lines = io.Source.fromFile("input.txt").getLines
val seventhLine = lines drop(6) next</lang>
val seventhLine = lines drop(6) next</syntaxhighlight>
===Imperative version===
===Imperative version===
Solving the task to the letter, imperative version:
Solving the task to the letter, imperative version:


<lang scala>var lines: Iterator[String] = _
<syntaxhighlight lang="scala">var lines: Iterator[String] = _
try {
try {
lines = io.Source.fromFile("input.txt").getLines drop(6)
lines = io.Source.fromFile("input.txt").getLines drop(6)
Line 2,005: Line 2,005:
else seventhLine = lines next
else seventhLine = lines next
}
}
if ("" == seventhLine) println("line is empty")</lang>
if ("" == seventhLine) println("line is empty")</syntaxhighlight>
===Functional version (Recommanded)===
===Functional version (Recommanded)===
<lang scala>val file = try Left(io.Source.fromFile("input.txt")) catch {
<syntaxhighlight lang="scala">val file = try Left(io.Source.fromFile("input.txt")) catch {
case exc => Right(exc.getMessage)
case exc => Right(exc.getMessage)
}
}
val seventhLine = (for(f <- file.left;
val seventhLine = (for(f <- file.left;
line <- f.getLines.toStream.drop(6).headOption.toLeft("too few lines").left) yield
line <- f.getLines.toStream.drop(6).headOption.toLeft("too few lines").left) yield
if (line == "") Right("line is empty") else Left(line)).joinLeft</lang>
if (line == "") Right("line is empty") else Left(line)).joinLeft</syntaxhighlight>


=={{header|sed}}==
=={{header|sed}}==
To print the seventh line:
To print the seventh line:
<lang sed>sed -n 7p</lang>
<syntaxhighlight lang="sed">sed -n 7p</syntaxhighlight>
To print an error message, if no such line:
To print an error message, if no such line:
<lang sed>sed '7h;$!d;x;s/^$/Error: no such line/'</lang>
<syntaxhighlight lang="sed">sed '7h;$!d;x;s/^$/Error: no such line/'</syntaxhighlight>
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.)
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.)


Line 2,025: Line 2,025:
and reads the requested line with [http://seed7.sourceforge.net/libraries/file.htm#getln%28inout_file%29 getln] afterwards:
and reads the requested line with [http://seed7.sourceforge.net/libraries/file.htm#getln%28inout_file%29 getln] afterwards:


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const func string: getLine (inout file: aFile, in var integer: lineNum) is func
const func string: getLine (inout file: aFile, in var integer: lineNum) is func
Line 2,056: Line 2,056:
end if;
end if;
end if;
end if;
end func;</lang>
end func;</syntaxhighlight>


=={{header|SenseTalk}}==
=={{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.
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.
<lang sensetalk>put line 7 of file "example.txt" into theLine
<syntaxhighlight lang="sensetalk">put line 7 of file "example.txt" into theLine
</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func getNthLine(filename, n) {
<syntaxhighlight lang="ruby">func getNthLine(filename, n) {
var file = File.new(filename);
var file = File.new(filename);
file.open_r.each { |line|
file.open_r.each { |line|
Line 2,074: Line 2,074:


var line = getNthLine("/etc/passwd", 7);
var line = getNthLine("/etc/passwd", 7);
print line if defined line;</lang>
print line if defined line;</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>
<syntaxhighlight lang="smalltalk">
line := (StandardFileStream oldFileNamed: 'test.txt') contents lineNumber: 7.
line := (StandardFileStream oldFileNamed: 'test.txt') contents lineNumber: 7.
</syntaxhighlight>
</lang>


=={{header|SPL}}==
=={{header|SPL}}==
<lang spl>lines = #.readlines("test.txt")
<syntaxhighlight lang="spl">lines = #.readlines("test.txt")
#.output("Seventh line of text:")
#.output("Seventh line of text:")
? #.size(lines,1)<7
? #.size(lines,1)<7
Line 2,088: Line 2,088:
!
!
#.output(lines[7])
#.output(lines[7])
.</lang>
.</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
See '''[http://www.stata.com/help.cgi?use use]''' in Stata help, to load a dataset or a part of it.
See '''[http://www.stata.com/help.cgi?use use]''' in Stata help, to load a dataset or a part of it.


<lang stata>* Read rows 20 to 30 from somedata.dta
<syntaxhighlight lang="stata">* Read rows 20 to 30 from somedata.dta
. use somedata in 20/30, clear
. use somedata in 20/30, clear


* Read rows for which the variable x is positive
* Read rows for which the variable x is positive
. use somedata if x>0, clear</lang>
. 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:
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:


<lang stata>capture use somedata in 7, clear
<syntaxhighlight lang="stata">capture use somedata in 7, clear
if _rc {
if _rc {
display "Too few lines"
display "Too few lines"
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{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).
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).
<lang tcl>proc getNthLineFromFile {filename n} {
<syntaxhighlight lang="tcl">proc getNthLineFromFile {filename n} {
set f [open $filename]
set f [open $filename]
while {[incr n -1] > 0} {
while {[incr n -1] > 0} {
Line 2,120: Line 2,120:
}
}


puts [getNthLineFromFile example.txt 7]</lang>
puts [getNthLineFromFile example.txt 7]</syntaxhighlight>
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.
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.


Line 2,152: Line 2,152:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>$$ MODE TUSCRIPT
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
file="lines.txt"
file="lines.txt"
ERROR/STOP OPEN (file,READ,-std-)
ERROR/STOP OPEN (file,READ,-std-)
line2fetch=7</lang>
line2fetch=7</syntaxhighlight>


=={{header|TXR}}==
=={{header|TXR}}==
===From the top===
===From the top===
Variable "line" matches and takes eighth line of input:
Variable "line" matches and takes eighth line of input:
<lang txr>@(skip nil 7)
<syntaxhighlight lang="txr">@(skip nil 7)
@line</lang>
@line</syntaxhighlight>


===From the bottom===
===From the bottom===
Take the third line from the bottom of the file, if it exists.
Take the third line from the bottom of the file, if it exists.
<lang txr>@(skip)
<syntaxhighlight lang="txr">@(skip)
@line
@line
@(skip 1 2)
@(skip 1 2)
@(eof)</lang>
@(eof)</syntaxhighlight>
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.
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.


Line 2,174: Line 2,174:
{{trans|Tcl}}
{{trans|Tcl}}
{{works with|bash}}
{{works with|bash}}
<lang bash>get_nth_line() {
<syntaxhighlight lang="bash">get_nth_line() {
local file=$1 n=$2 line
local file=$1 n=$2 line
while ((n-- > 0)); do
while ((n-- > 0)); do
Line 2,185: Line 2,185:
}
}


get_nth_line filename 7</lang>
get_nth_line filename 7</syntaxhighlight>


You can also use standard tools instead of built-ins:.
You can also use standard tools instead of built-ins:.


<lang bash>awk NR==7 filename
<syntaxhighlight lang="bash">awk NR==7 filename
sed -n 7p filename
sed -n 7p filename
head -n 7 filename | tail -n 1</lang>
head -n 7 filename | tail -n 1</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>decl string<> lines
<syntaxhighlight lang="ursa">decl string<> lines
decl file f
decl file f
f.open "filename.txt"
f.open "filename.txt"
Line 2,206: Line 2,206:


out "the seventh line in the file is:" endl endl console
out "the seventh line in the file is:" endl endl console
out lines<6> endl console</lang>
out lines<6> endl console</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function read_line(filepath,n)
Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Line 2,228: Line 2,228:


WScript.Echo read_line("c:\temp\input.txt",7)
WScript.Echo read_line("c:\temp\input.txt",7)
</syntaxhighlight>
</lang>


{{In}}
{{In}}
Line 2,248: Line 2,248:
This example reads the 7th line (including newline character(s)) into text register 10.
This example reads the 7th line (including newline character(s)) into text register 10.


<lang vedit>File_Open("example.txt", BROWSE)
<syntaxhighlight lang="vedit">File_Open("example.txt", BROWSE)
Goto_Line(7)
Goto_Line(7)
if (Cur_Line < 7) {
if (Cur_Line < 7) {
Line 2,258: Line 2,258:
Reg_Copy(10, 1)
Reg_Copy(10, 1)
}
}
Buf_Close(NOMSG) </lang>
Buf_Close(NOMSG) </syntaxhighlight>


If the file does not exist, the buffer will be empty and you get "File contains too few lines" error.
If the file does not exist, the buffer will be empty and you get "File contains too few lines" error.
Line 2,267: Line 2,267:
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang ecmascript>import "io" for File
<syntaxhighlight lang="ecmascript">import "io" for File


var lines = File.read("input.txt").replace("\r", "").split("\n")
var lines = File.read("input.txt").replace("\r", "").split("\n")
Line 2,290: Line 2,290:
Line 7
Line 7
Line 8
Line 8
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 2,301: Line 2,301:
Usage: readline <filename.ext
Usage: readline <filename.ext


<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
def MaxLen = 82; \maximum length of line that can be stored (incl CR+LF)
def MaxLen = 82; \maximum length of line that can be stored (incl CR+LF)


Line 2,326: Line 2,326:


char LineN(MaxLen);
char LineN(MaxLen);
if ReadLine(7, LineN) then Text(0, LineN)</lang>
if ReadLine(7, LineN) then Text(0, LineN)</syntaxhighlight>


=={{header|zkl}}==
=={{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.
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.
<lang zkl>reg line; do(7){line=File.stdin.readln()} println(">>>",line);</lang>
<syntaxhighlight lang="zkl">reg line; do(7){line=File.stdin.readln()} println(">>>",line);</syntaxhighlight>
Or, suck in lines and take the last one:
Or, suck in lines and take the last one:
<lang zkl>lines:=File.stdin.readln(7); println(">>>",line[-1]);</lang>
<syntaxhighlight lang="zkl">lines:=File.stdin.readln(7); println(">>>",line[-1]);</syntaxhighlight>