Read a specific line from a file: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
(→{{header|PL/M}}: Added note.) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(26 intermediate revisions by 15 users not shown) | |||
Line 6:
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded).
If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message.
If no special semantics are available for obtaining the required line, it is permissible to read line by line.
Note that empty lines are considered and should still be counted.
Also note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
<br><br>
=={{header|11l}}==
<
V line = 3
L 0 .< line - 1
f.read_line()
print(f.read_line())</
=={{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.
<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)
Open(dev,fname,4)
curr=1 status=1
WHILE Eof(dev)=0
DO
InputSD(dev,line)
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)
CHAR ARRAY result(255)
BYTE status
PrintF("Reading %U line...%E",index)
status=ReadLine(fname,index,result)
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}}==
<
procedure Rosetta_Read is
Line 46 ⟶ 119:
Put_Line ("Line 7 is too long to load.");
Close (File);
end Rosetta_Read;</
=={{header|Aime}}==
<
read_line(text &line, text path, integer n)
{
Line 74 ⟶ 147:
0;
}</
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<
# from the file named "file name" and returns the text of the #
# in "line". If an error occurs, the result is FALSE and a #
Line 88 ⟶ 161:
, REF STRING err
)BOOL:
IF FILE input file;
line := "";
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
Line 118 ⟶ 184:
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 #
Line 146 ⟶ 206:
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
Line 167 ⟶ 220:
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}}==
<
if ErrorLevel
MsgBox, There was an error reading the 7th line of the file</
=={{header|AWK}}==
<
#usage: readnthline.awk -v lineno=6 filename
Line 192 ⟶ 271:
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}}==
<
@echo off
Line 205 ⟶ 369:
echo Line 7 is: %line7%
pause>nul
</syntaxhighlight>
{{in}}
<pre>
Line 225 ⟶ 389:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
requiredline% = 7
Line 237 ⟶ 401:
IF ASCtext$=10 text$ = MID$(text$,2)
PRINT text$</
=={{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.
<
#include <sys/types.h>
#include <sys/mman.h>
Line 306 ⟶ 470:
return ret;
}</
===Alternate Version===
Line 312 ⟶ 476:
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.
<
#include <stdlib.h>
Line 413 ⟶ 577:
return 0;
}
</syntaxhighlight>
=={{header|C sharp}}==
<
using System.IO;
Line 460 ⟶ 624:
}
}
}</
=={{header|C++}}==
<
#include <fstream>
#include <iostream>
Line 496 ⟶ 660:
return 1 ;
}
}</
=={{header|Clojure}}==
<
"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))))</
{{out}}
Line 511 ⟶ 675:
=={{header|Common Lisp}}==
<
"Read the nth line from a text file. The first line has the number 1"
(assert (> n 0) (n))
Line 522 ⟶ 686:
if (and line (= line-number n))
do (return line))))
</syntaxhighlight>
Example call:
Line 530 ⟶ 694:
=={{header|D}}==
simply
<syntaxhighlight lang="d">
void main() {
import std.stdio, std.file, std.string;
Line 537 ⟶ 701:
writeln((file_lines.length > 6) ? file_lines[6] : "line not found");
}
</syntaxhighlight>
or, line by line
<
void main() {
Line 561 ⟶ 725:
writefln("the file only contains %d lines", countLines);
}
}</
<pre>
line 7: foreach (char[] line; f.byLine()) {</pre>
Line 567 ⟶ 731:
{{libheader| System.SysUtils}}
{{Trans|Pascal}}
<syntaxhighlight lang="delphi">
program Read_a_specific_line_from_a_file;
Line 605 ⟶ 769:
Writeln(ReadLine(7, 'test'));
Readln;
end.</
=={{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
Line 621 ⟶ 785:
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">
-module( read_a_specific_line ).
Line 657 ⟶ 821:
line_nr_error( function_clause ) -> too_few_lines_in_file;
line_nr_error( Error ) -> Error.
</syntaxhighlight>
{{out}}
Line 674 ⟶ 838:
=={{header|F_Sharp|F#}}==
<
open System.IO
Line 688 ⟶ 852:
// if not not enough lines available
Console.WriteLine(line)
0</
=={{header|Factor}}==
<
math ;
IN: rosetta-code.nth-line
Line 705 ⟶ 869:
print ;
MAIN: nth-line-demo</
=={{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.<
CONTAINS SAM00200
CHARACTER*20 FUNCTION GETREC(N,F,IS) !Returns a status. SAM00300
Line 777 ⟶ 941:
666 WRITE (MSG,*) "Can't get the record!" POK02700
END !That was easy. POK02800
</syntaxhighlight>
Output:
<pre>
Line 797 ⟶ 961:
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 <
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: <
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</
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}}==
<
Open "input.txt" For Input As #1
Line 833 ⟶ 997:
Print
Print "Press any key to quit"
Sleep </
=={{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
<
if ( url )
open "I", 2, url
while ( not eof(2) )
line input #2, s
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:
Line 882 ⟶ 1,060:
=={{header|Go}}==
<
import (
Line 932 ⟶ 1,110:
}
return line, nil
}</
=={{header|Groovy}}==
<
new File("lines.txt").eachLine { currentLine, lineNumber ->
if (lineNumber == 7) {
Line 941 ⟶ 1,119:
}
}
println "Line 7 = $line"</
=={{header|Haskell}}==
<
main = do contents <- readFile filename
case drop 6 $ lines contents of
[] -> error "File has less than seven lines"
l:_ -> putStrLn l
where filename = "testfile"</
=={{header|Icon}} and {{header|Unicon}}==
Line 957 ⟶ 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.
<
write(readline("foo.bar.txt",7)|"failed")
end
Line 966 ⟶ 1,144:
close(f)
if i = 0 then return line
end</
=={{header|J}}==
<
(x-1) {:: <;.2 ] 1!:1 boxxopen y
)</
Thus:
<
<
9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19</
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'''
<
readLineT=: <:@[ {:: 'b'&freads@]</
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 989 ⟶ 1,167:
<tt>example: java -cp . LineNbr7 LineNbr7.java</tt><br>
<tt>output : line 7: public static void main(String[] args) throws Exception {;</tt>
<
import java.io.*;
Line 1,021 ⟶ 1,199:
}
}
}</
===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}}==
Line 1,030 ⟶ 1,236:
* "foreach" - a control structure for iterating over a stream
* "break" - for breaking out of a loop
<
# Output - a stream with 0 or 1 items
def read_line:
Line 1,036 ⟶ 1,242:
| label $top
| foreach inputs as $line
(0; .+1; if . == $in then $line, break $top else empty end) ;</
'''Example:''' Read line number $line (to be provided on the command line), counting from 1
<
| if . > 0 then read_line
else "$line (\(.)) should be a non-negative integer"
end</
{{out}}
<
9</
=={{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 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.
<
for i = 1:num-1
readline(stream)
Line 1,056 ⟶ 1,262:
result = readline(stream)
print(result != "" ? result : "No such line.")
end</
{{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}}==
<
import java.io.File
Line 1,093 ⟶ 1,308:
Line 7
Line 8
*/</
{{out}}
Line 1,101 ⟶ 1,316:
=={{header|Lasso}}==
<
handle => { #f->close }
local(this_line = string,line = 0)
Line 1,110 ⟶ 1,325:
}
#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.
<
requiredLine =7
Line 1,124 ⟶ 1,339:
if line7$ =chr$( 13) +chr$( 10) or line7$ ="" then notice "Empty line! ( or file has fewer lines)."
print line7$</
=={{header|Lua}}==
<
local count = 0
for line in io.lines(fileName) do
Line 1,136 ⟶ 1,351:
end
print(fileLine(7, "test.txt"))</
=={{header|Maple}}==
<
specificLine := proc(path, num)
local i, input:
Line 1,148 ⟶ 1,363:
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:</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
eln = 7; % extract line number 7
line = '';
Line 1,174 ⟶ 1,389:
end;
printf('line %i: %s\n',eln,line);
</
<nowiki>Insert non-formatted text here</nowiki>
=={{header|MoonScript}}==
{{trans|Lua}}
<
for i=0, 5
error 'Not 7 lines in file' if not iter!
print iter!</
=={{header|Nanoquery}}==
<
contents = null
try
Line 1,198 ⟶ 1,413:
end
end
end</
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 1,253 ⟶ 1,468:
method isFalse() public static returns boolean
return \(1 == 1)
</syntaxhighlight>
=={{header|Nim}}==
<
proc readLine(f: File; num: Positive): string =
Line 1,269 ⟶ 1,484:
echo f.readLine(7)
f.close()
</syntaxhighlight>
=={{header|OCaml}}==
Line 1,275 ⟶ 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:
<
try Some (input_line ic)
with End_of_file -> None
Line 1,295 ⟶ 1,510:
let () =
print_endline (nth_line 7 Sys.argv.(1))</
=={{header|PARI/GP}}==
Line 1,302 ⟶ 1,517:
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<
uses
Line 1,339 ⟶ 1,554:
Close(myfile);
writeln(line);
end.</
Output:
<pre>
Line 1,346 ⟶ 1,561:
=={{header|Perl}}==
<
# invoke as <scriptname> -n=7 [input]
while (<>) { $. == $n and print, exit }
die "file too short\n";</
=={{header|Phix}}==
No specific mechanism, but simple enough. If the file is suitably small:
<!--<
<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>
Line 1,360 ⟶ 1,575:
<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>
<!--</
For bigger files:
<!--<
<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>
Line 1,369 ⟶ 1,584:
<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>
<!--</
=={{header|Phixmonti}}==
<
argument 1 get "r" fopen var f drop
Line 1,379 ⟶ 1,594:
f fgets number? if f fclose exitfor else nip nip endif
endfor
print /# show -1 if past eof #/</
=={{header|PHP}}==
<
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
Line 1,398 ⟶ 1,613:
if (!$fp) die("Input file not found!");
echo fileLine(7, $fp);
?></
=={{header|PicoLisp}}==
<
(do 6 (line))
(or (line) (quit "No 7 lines")) )</
=={{header|PL/I}}==
<syntaxhighlight lang="pli">
declare text character (1000) varying, line_no fixed;
Line 1,419 ⟶ 1,634:
put skip list (text);
next: ;
</syntaxhighlight>
=={{header|PL/M}}==
This is written for the original 8080 PL/M compiler and can be run under CP/M
<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.
<syntaxhighlight lang="pli">100H: /* READ A SPECIFIC LINE FROM A FILE */
DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';
Line 1,555 ⟶ 1,771:
CALL EXIT;
EOF</
=={{header|PowerShell}}==
{{works with|PowerShell|3.0}}
<syntaxhighlight lang="powershell">
$file = Get-Content c:\file.txt
if ($file.count -lt 7)
Line 1,567 ⟶ 1,783:
$file | Where Readcount -eq 7 | set-variable -name Line7
}
</syntaxhighlight>
=={{header|PureBasic}}==
<
lineRead.i
line.s
Line 1,601 ⟶ 1,817:
MessageRequester("Error", "Couldn't open file " + filename + ".")
EndIf
EndIf </
=={{header|Python}}==
Line 1,607 ⟶ 1,823:
Using only builtins (note that <code>enumerate</code> is zero-based):
<
for i, line in enumerate(f):
if i == 6:
Line 1,613 ⟶ 1,829:
else:
print('Not 7 lines in file')
line = None</
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:
<
with open('xxx.txt') as f:
Line 1,623 ⟶ 1,839:
line = next(islice(f, 6, 7))
except StopIteration:
print('Not 7 lines in file')</
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.
<
print open('xxx.txt').readlines()[:7][-1]
</syntaxhighlight>
=={{header|R}}==
<
Read 0 items
> seven <- scan('Incoming/quotes.txt', '', skip = 6, nlines = 1, sep = '\n')
Read 1 item
</syntaxhighlight>
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 1,648 ⟶ 1,864:
(call-with-input-file "some-file"
(λ(i) (for/last ([line (in-lines i)] [n 7]) line))))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
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
Line 1,665 ⟶ 1,881:
=={{header|REBOL}}==
<
x: pick read/lines request-file/only 7
either x [print x] [print "No seventh line"]
</syntaxhighlight>
=={{header|Red}}==
<
case [
Line 1,677 ⟶ 1,893:
(length? x) = 0 [print "Line 7 is empty"]
(length? x) > 0 [print append "Line seven = " x]
]</
=={{header|REXX}}==
===for newer REXXes===
<
parse arg FID n . /*obtain optional arguments from the CL*/
if FID=='' | FID=="," then FID= 'JUNK.TXT' /*not specified? Then use the default.*/
Line 1,698 ⟶ 1,914:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser: say; say '***error!*** File ' FID " " arg(1); say; exit 13</
===for older REXXes===
Some older REXXes don't support a 2<sup>nd</sup> argument for the '''linein''' BIF, so here is an alternative:
<
parse arg FID n . /*obtain optional arguments from the CL*/
if FID=='' | FID=="," then FID= 'JUNK.TXT' /*not specified? Then use the default.*/
Line 1,722 ⟶ 1,938:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser: say; say '***error!*** File ' FID " " arg(1); say; exit 13</
<br><br>
=={{header|Ring}}==
<
fp = fopen("C:\Ring\ReadMe.txt","r")
n = 0
Line 1,739 ⟶ 1,955:
end
fclose(fp)
</syntaxhighlight>
=={{header|Ruby}}==
The each_line method returns an Enumerator, so no more than seven lines are read.
<
</syntaxhighlight>
=={{header|Run BASIC}}==
<
requiredLine = 7
open fileName$ for input as #f
Line 1,756 ⟶ 1,972:
close #f
print a$
end</
=={{header|Rust}}==
<
use std::io::BufRead;
use std::io::BufReader;
Line 1,777 ⟶ 1,993:
let mut lines = content.lines();
lines.nth(line_num).expect("No line found at that position")
}</
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.
<
use std::fs::File;
use std::io::BufRead;
Line 1,811 ⟶ 2,027:
let line = lines.nth(line_num).expect("No line found at given position");
println!("{}", line.expect("None line"));
}</
=={{header|Scala}}==
Line 1,817 ⟶ 2,033:
The code will throw a <tt>NoSuchElementException</tt> if the file doesn't have 7 lines.
<
val seventhLine = lines drop(6) next</
===Imperative version===
Solving the task to the letter, imperative version:
<
try {
lines = io.Source.fromFile("input.txt").getLines drop(6)
Line 1,834 ⟶ 2,050:
else seventhLine = lines next
}
if ("" == seventhLine) println("line is empty")</
===Functional version (Recommanded)===
<
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</
=={{header|sed}}==
To print the seventh line:
<syntaxhighlight lang
To print an error message, if no such 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 1,854 ⟶ 2,070:
and reads the requested line with [http://seed7.sourceforge.net/libraries/file.htm#getln%28inout_file%29 getln] afterwards:
<
const func string: getLine (inout file: aFile, in var integer: lineNum) is func
Line 1,885 ⟶ 2,101:
end if;
end if;
end func;</
=={{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>
=={{header|Sidef}}==
<
var file = File
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)
=={{header|Smalltalk}}==
<
line := (StandardFileStream oldFileNamed: 'test.txt') contents lineNumber: 7.
</syntaxhighlight>
=={{header|SPL}}==
<
#.output("Seventh line of text:")
? #.size(lines,1)<7
Line 1,917 ⟶ 2,133:
!
#.output(lines[7])
.</
=={{header|Stata}}==
See '''[http://www.stata.com/help.cgi?use use]''' in Stata help, to load a dataset or a part of it.
<
. use somedata in 20/30, clear
* Read rows for which the variable x is positive
. use somedata if x>0, clear</
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 _rc {
display "Too few lines"
}</
=={{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).
<
set f [open $filename]
while {[incr n -1] > 0} {
Line 1,949 ⟶ 2,165:
}
puts [getNthLineFromFile example.txt 7]</
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 1,981 ⟶ 2,197:
=={{header|TUSCRIPT}}==
<
file="lines.txt"
ERROR/STOP OPEN (file,READ,-std-)
line2fetch=7</
=={{header|TXR}}==
===From the top===
Variable "line" matches and takes eighth line of input:
<
@line</
===From the bottom===
Take the third line from the bottom of the file, if it exists.
<
@line
@(skip 1 2)
@(eof)</
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,003 ⟶ 2,219:
{{trans|Tcl}}
{{works with|bash}}
<
local file=$1 n=$2 line
while ((n-- > 0)); do
Line 2,014 ⟶ 2,230:
}
get_nth_line filename 7</
You can also use standard tools instead of built-ins:.
<syntaxhighlight lang="bash">awk NR==7 filename
sed -n 7p filename
head -n 7 filename | tail -n 1</syntaxhighlight>
=={{header|Ursa}}==
<
decl file f
f.open "filename.txt"
Line 2,029 ⟶ 2,251:
out "the seventh line in the file is:" endl endl console
out lines<6> endl console</
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Line 2,051 ⟶ 2,273:
WScript.Echo read_line("c:\temp\input.txt",7)
</syntaxhighlight>
{{In}}
Line 2,071 ⟶ 2,293:
This example reads the 7th line (including newline character(s)) into text register 10.
<
Goto_Line(7)
if (Cur_Line < 7) {
Line 2,081 ⟶ 2,303:
Reg_Copy(10, 1)
}
Buf_Close(NOMSG) </
If the file does not exist, the buffer will be empty and you get "File contains too few lines" error.
Line 2,090 ⟶ 2,312:
=={{header|Wren}}==
{{trans|Kotlin}}
<
var lines = File.read("input.txt").replace("\r", "").split("\n")
Line 2,113 ⟶ 2,335:
Line 7
Line 8
*/</
{{out}}
Line 2,124 ⟶ 2,346:
Usage: readline <filename.ext
<
def MaxLen = 82; \maximum length of line that can be stored (incl CR+LF)
Line 2,149 ⟶ 2,371:
char LineN(MaxLen);
if ReadLine(7, LineN) then Text(0, LineN)</
=={{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.
<
Or, suck in lines and take the last one:
<
|