Read a file line by line: Difference between revisions

Add Standard ML version
(Add Standard ML version)
(40 intermediate revisions by 27 users not shown)
Line 18:
=={{header|360 Assembly}}==
This program uses OS QSAM I/O macros (OPEN,CLOSE,GET,PUT,DCB).
<langsyntaxhighlight lang="360asm">* Read a file line by line 12/06/2016
READFILE CSECT
SAVE (14,12) save registers on entry
Line 50:
PG DS CL80 buffer
YREGS
END READFILE</langsyntaxhighlight>
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
"path/to/file" f:open ( . cr ) f:eachline f:close
</syntaxhighlight>
</lang>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program readfile64.s */
Line 238:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<syntaxhighlight lang="text">char array TXT
 
Proc Main()
 
Open (1,"D:FILENAME.TXT",4,0)
Do
InputSD(1,TXT)
PrintE(TXT)
Until EOF(1)
Od
Close(1)
 
Return
</syntaxhighlight>
 
=={{header|Ada}}==
{{works with|Ada 2005}}
line_by_line.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Line_By_Line is
Line 257 ⟶ 273:
Close (File);
end Line_By_Line;
</syntaxhighlight>
</lang>
 
{{Out}}
Line 277 ⟶ 293:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">file f;
text s;
 
Line 285 ⟶ 301:
o_text(s);
o_byte('\n');
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 291 ⟶ 307:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.3.5 algol68g-2.3.5].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''File: ./Read_a_file_line_by_line.a68'''<langsyntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #
 
FILE foobar;
Line 311 ⟶ 327:
printf(($g(0)": "$, count, line fmt, line))
OD;
done: SKIP</langsyntaxhighlight>
{{out}}
<pre style="height:15ex;overflow:scroll">
Line 337 ⟶ 353:
</pre>
 
=={{header|APL}}==
<syntaxhighlight lang="apl">
⍝⍝ GNU APL Version
∇listFile fname ;fileHandle;maxLineLen;line
maxLineLen ← 128
fileHandle ← ⎕FIO['fopen'] fname
readLoop:
→(0=⍴(line ← maxLineLen ⎕FIO['fgets'] fileHandle))/eof
⍞ ← ⎕AV[1+line] ⍝⍝ bytes to ASCII
→ readLoop
eof:
⊣⎕FIO['fclose'] fileHandle
⊣⎕FIO['errno'] fileHandle
 
listFile 'corpus/sample1.txt'
This is some sample text.
The text itself has multiple lines, and
the text has some words that occur multiple times
in the text.
 
This is the end of the text.
 
</syntaxhighlight>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
 
main:
.ctrlc
fd=0
fopen(OPEN_READ,"archivo.txt")(fd)
if file error?
{"Error open file: "},file error
else
line read=0
while( not(feof(fd)))
fread line(1000)(fd), ++line read
println
wend
{"Total read lines : ",line read}
fclose(fd)
endif
println
exit(0)
</syntaxhighlight>
{{out}}
<pre>
RX/RY,A,B,C,D,E,F,G,H,I,J
fila 1,1,2,3,4,5,6,7.998,8,9.034,10
fila 2,10,20,30,40,50,60,70,80,90,100
fila 3,100,200,300.5,400,500,600,700,800,900,1000
fila 4,5,10,15,20,25,30,35,40,45,50
fila 5,a,b,c,d,e,f,g,h,i,j
fila 6,1,2,3,4,5,6,7,8,9,10
Total read lines : 7
</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program readfile.s */
Line 624 ⟶ 698:
iMagicNumber: .int 0xCCCCCCCD
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">loop read.lines "myfile.txt" 'line ->
print line</syntaxhighlight>
 
=={{header|Astro}}==
<langsyntaxhighlight lang="python">for line in lines open('input.txt'):
print line
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
 
<langsyntaxhighlight AutoHotkeylang="autohotkey">; --> Prompt the user to select the file being read
 
FileSelectFile, File, 1, %A_ScriptDir%, Select the (text) file to read, Documents (*.txt) ; Could of course be set to support other filetypes
Line 653 ⟶ 732:
FileDelete, Output.txt ; Makes sure output is clear before writing
FileAppend, %Text%, Output.txt ; Writes the result to Output.txt
Run Output.txt ; Shows the created file</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 659 ⟶ 738:
 
'''One-liner:'''
<langsyntaxhighlight AWKlang="awk">awk '{ print $0 }' filename</langsyntaxhighlight>
 
'''Shorter:'''<br>
Line 666 ⟶ 745:
so this is the shortest possible awk-program
(not counting the [[Empty program]]):
<langsyntaxhighlight AWKlang="awk">awk '1' filename</langsyntaxhighlight>
 
'''Longer:'''<br>
Reading several files, with some processing:
<langsyntaxhighlight AWKlang="awk"># usage: awk -f readlines.awk *.txt
BEGIN { print "# Reading..." }
FNR==1 { f++; print "# File #" f, ":", FILENAME }
Line 678 ⟶ 757:
{ print } # same as "print $0"
END { print "# Done with", f, "file(s), with a total of", NR, "lines." }
END { print "# Comment-lines:", c }</langsyntaxhighlight>
Note:
* The variables c and f are initialized automatically to 0
Line 707 ⟶ 786:
 
==={{header|BaCon}}===
<langsyntaxhighlight lang="freebasic">' Read a file line by line
filename$ = "readlines.bac"
OPEN filename$ FOR READING AS fh
Line 716 ⟶ 795:
WEND
PRINT lines, " lines in ", filename$
CLOSE FILE fh</langsyntaxhighlight>
 
{{out}}
Line 723 ⟶ 802:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 INPUT PROMPT "Filename: ":NAME$
110 OPEN #1:NAME$ ACCESS INPUT
120 COPY FROM #1 TO #0
130 CLOSE #1</langsyntaxhighlight>
 
==={{header|Locomotive Basic}}===
<syntaxhighlight lang="locobasic">10 OPENIN"foo.txt"
 
<lang locobasic>10 OPENIN"foo.txt"
20 WHILE NOT EOF
30 LINE INPUT#9,i$
40 PRINT i$
50 WEND</langsyntaxhighlight>
 
==={{header|OxygenBasic}}===
The core function '''GetFile''' reads the whole file:
<syntaxhighlight lang="oxygenbasic">
function getline(string s, int *i) as string
int sl=i, el=i
byte b at strptr(s)
do
select b[el]
case 0
i=el+1 : exit do
case 10 'lf
i=el+1 : exit do
case 13 'cr
i=el+1
if b[i]=10 then i++ 'crlf
exit do
end select
el++
loop
return mid(s,sl,el-sl)
end function
'read all file lines
'===================
string s=getfile "t.txt"
int le=len(s)
int i=1
int c=0
string wr
if le=0 then goto done
do
wr = getline(s,i)
'print wr
c++
if i>le then exit do
end do
done:
print "Line count " c
</syntaxhighlight>
 
==={{header|QBasic}}===
{{works with|QBasic}}
{{works with|QuickBasic}}
<syntaxhighlight lang="qbasic">f = FREEFILE
filename$ = "file.txt"
OPEN filename$ FOR INPUT AS #f
 
WHILE NOT EOF(f)
LINE INPUT #f, linea$
PRINT linea$
WEND
CLOSE #f
END</syntaxhighlight>
 
==={{header|uBasic/4tH}}===
uBasic/4tH only supports text files - and they can only be read line by line. '''READ()''' fills the line buffer. In order to pass (parts of) the line to a variable or function, the tokenizer function '''TOK()''' needs to be called with a specific delimiter. In order to parse the entire line in one go, the string terminator '''CHR(0)''' must be provided.
<syntaxhighlight lang="text">If Set (a, Open ("myfile.bas", "r")) < 0 Then Print "Cannot open \qmyfile.bas\q" : End
 
Do While Read (a)
Print Show(Tok(0))
Loop
 
Close a
</syntaxhighlight>
==={{header|ZX Spectrum Basic}}===
The tape recorder interface does not support fragmented reads, because tape recorder start and stop is not atomic, (and a leadin is required for tape input).
Line 741 ⟶ 885:
In the following example, we read a file line by line from a file on microdrive 1.
 
<langsyntaxhighlight lang="basic">10 REM open my file for input
20 OPEN #4;"m";1;"MYFILE": REM stream 4 is the first available for general purpose
30 INPUT #4; LINE a$: REM a$ will hold our line from the file
Line 747 ⟶ 891:
50 REM to gracefully exit when the file is read. (omitted from this example)
60 REM to prevent an error at end of file, place a handler here
100 GOTO 30</langsyntaxhighlight>
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">f = freefile
filename$ = "file.txt"
 
open f, filename$
 
while not eof(f)
print readline(f)
end while
close f
end</syntaxhighlight>
 
 
=={{header|Batch File}}==
This takes account on the blank lines, because FOR ignores blank lines when reading a file.
<langsyntaxhighlight lang="dos">@echo off
rem delayed expansion must be disabled before the FOR command.
setlocal disabledelayedexpansion
Line 759 ⟶ 916:
echo(!var!
endlocal
)</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
This method is appropriate if the lines are terminated by a single CR or LF:
<langsyntaxhighlight lang="bbcbasic"> file% = OPENIN("*.txt")
IF file%=0 ERROR 100, "File could not be opened"
WHILE NOT EOF#file%
a$ = GET$#file%
ENDWHILE
CLOSE #file%</langsyntaxhighlight>
This method is appropriate if the lines are terminated by a CRLF pair:
<langsyntaxhighlight lang="bbcbasic"> file% = OPENIN("*.txt")
IF file%=0 ERROR 100, "File could not be opened"
WHILE NOT EOF#file%
Line 777 ⟶ 934:
IF ASCa$=10 a$ = MID$(a$,2)
ENDWHILE
CLOSE #file%</langsyntaxhighlight>
 
=={{header|Bracmat}}==
<code>fil</code> is a relatively low level Bracmat function for manipulating files. Depending on the parameters it opens, closes, reads, writes a file or reads or sets the file position.
<langsyntaxhighlight lang="bracmat"> fil$("test.txt",r) { r opens a text file, rb opens a binary file for reading }
& fil$(,STR,\n) { first argument empty: same as before (i.e. "test.txt") }
{ if \n were replaced by e.g. "\n\t " we would read word-wise instead }
Line 790 ⟶ 947:
)
& (fil$(,SET,-1)|); { Setting file position before start closes file, and fails.
Therefore the | }</langsyntaxhighlight>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">include :file
 
file.each_line "foobar.txt" { line |
p line
}</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">/* Programa: Número mayor de tres números introducidos (Solución 1) */
 
#include <conio.h>
Line 828 ⟶ 985:
 
return 0;
}</langsyntaxhighlight>
 
===with getline===
<langsyntaxhighlight Clang="c">// From manpage for "getline"
 
#include <stdio.h>
Line 855 ⟶ 1,012:
fclose(stream);
exit(EXIT_SUCCESS);
}</langsyntaxhighlight>
 
=== Using mmap() ===
Implementation using mmap syscall. Works on Linux 2.6.* and on *BSDs. Line reading routine takes a callback function, each line is passed into callback as begin and end pointer. Let OS handle your memory pages, we don't need no stinking mallocs.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h> /* C POSIX library file control options */
#include <unistd.h> /* C POSIX library system calls: open, close */
#include <sys/mman.h> /* memory management declarations: mmap, munmap */
#include <errno.h> /* Std C library system error numbers: errno */
#include <err.h> /* GNU C lib error messages: err */
 
int read_lines(const char * fname, int (*call_back)(const char*, const char*))
Line 934 ⟶ 1,091:
return read_lines("test.ps", print_line) ? 0 : 1;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp}}==
'File.ReadLines' reads the lines of a file which could easily be stepped through.
<langsyntaxhighlight lang="csharp">foreach (string readLine in File.ReadLines("FileName"))
DoSomething(readLine);</langsyntaxhighlight>
A full code may look like;
<langsyntaxhighlight lang="csharp">using System;
using System.IO;
using System.Text;
Line 974 ⟶ 1,131:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{works with|C++03 to C++17 }}
<langsyntaxhighlight lang="cpp">#include <fstream>
#include <string>
#include <iostream>
Line 995 ⟶ 1,152:
infile.close( ) ;
return 0 ;
}</langsyntaxhighlight>
 
====using std::getline====
Line 1,008 ⟶ 1,165:
</pre>
 
<langsyntaxhighlight lang="cpp">
#include <fstream>
#include <iostream>
Line 1,028 ⟶ 1,185:
}
std::cout << "finished" << std::endl;
}</langsyntaxhighlight>
 
{{out}}
Line 1,043 ⟶ 1,200:
{{libheader|U++}}
 
<langsyntaxhighlight lang="cpp">#include <Core/Core.h>
 
using namespace Upp;
Line 1,052 ⟶ 1,209:
while(in && !in.IsEof())
Cout().PutLine(in.GetLine());
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
 
<syntaxhighlight lang="clojure">
<lang Clojure>
(with-open [r (clojure.java.io/reader "some-file.txt")]
(doseq [l (line-seq r)]
(println l)))
</syntaxhighlight>
</lang>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">start_up = proc ()
po: stream := stream$primary_output()
% There is a special type for file names. This ensures that
% the path is valid; if not, file_name$parse would throw an
% exception (which we are just ignoring here).
fname: file_name := file_name$parse("input.txt")
% File I/O is then done through a stream just like any I/O.
% If the file were not accessible, stream$open would throw an
% exception.
fstream: stream := stream$open(fname, "read")
count: int := 0 % count the lines
while true do
% Read a line. This will end the loop once the end is reached,
% as the exception handler is outside the loop.
line: string := stream$getl(fstream)
% Show the line
count := count + 1
stream$putl(po, int$unparse(count) || ": " || line)
end except when end_of_file:
% Close the file once we're done
stream$close(fstream)
end
end start_up</syntaxhighlight>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. read-file-line-by-line.
 
Line 1,100 ⟶ 1,286:
 
GOBACK
.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
{{works_with|node.js}}
<langsyntaxhighlight lang="coffeescript">
# This module shows two ways to read a file line-by-line in node.js.
fs = require 'fs'
Line 1,185 ⟶ 1,371:
console.log "DONE ASYNC!"
reader.next_line callbacks.process_line, callbacks.all_done
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(with-open-file (input "file.txt")
(loop for line = (read-line input nil)
while line do (format t "~a~%" line)))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio;
 
foreach (line; "read_a_file_line_by_line.d".File.byLine)
line.writeln;
}</langsyntaxhighlight>
The File is managed by reference count, and it gets closed when it gets out of scope or it changes. The 'line' is a char[] (with newline), so if you need a string you have to idup it.
 
=={{header|DBL}}==
<syntaxhighlight lang="dbl">;
; Read a file line by line for DBL version 4
;
RECORD
 
LINE, A100
 
PROC
;-----------------------------------------------
OPEN (1,I,"FILE.TXT") [ERR=NOFIL]
DO FOREVER
BEGIN
READS (1,LINE,EOF) [ERR=EREAD]
END
EOF, CLOSE 3
GOTO CLOS
 
;------------------------------------------------
NOFIL, ;Open error...do something
GOTO CLOS
 
EREAD, ;Read error...do something
GOTO CLOS
 
CLOS, STOP</syntaxhighlight>
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="dcl">$ open input input.txt
$ loop:
$ read /end_of_file = done input line
$ goto loop
$ done:
$ close input</langsyntaxhighlight>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
procedure ReadFileByLine;
var
Line 1,222 ⟶ 1,436:
CloseFile(TextFile);
end;
</syntaxhighlight>
</lang>
The example file (above) '''"c:\test.txt"''' is assigned to the text file variable '''"TextFile"''' is opened and any line is read in a loop into the string variable '''"TextLine"'''.
 
<syntaxhighlight lang="delphi">
<lang Delphi>
procedure ReadFileByLine;
var
Line 1,236 ⟶ 1,450:
ShowMessage(TextLines[i]);
end;
</syntaxhighlight>
</lang>
 
Above uses the powerful utility classs type [http://www.delphibasics.co.uk/RTL.asp?Name=TStringList TStringList] from Classes Unit
 
See also GNU LGPL (Delphi replacement) [http://www.lazarus.freepascal.org/ Lazarus IDE FreePascal] and specifically [http://wiki.lazarus.freepascal.org/TString_List-TString_Tutorial Lazarus FreePascal Equivalent for TStringList]
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">\util.g
proc nonrec main() void:
/* first we need to declare a file buffer and an input channel */
file() infile;
channel input text in_ch;
/* a buffer to store the line in is also handy */
[256] char line;
word counter; /* to count the lines */
/* open the file, and exit if it fails */
if not open(in_ch, infile, "input.txt") then
writeln("cannot open file");
exit(1)
fi;
counter := 0;
/* readln() reads a line and will return false once the end is reached */
/* we pass in a pointer so it stores a C-style zero-terminated string,
* rather than try to fill the entire array */
while readln(in_ch; &line[0]) do
counter := counter + 1;
writeln(counter:5, ": ", &line[0])
od;
/* finally, close the file */
close(in_ch)
corp</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import system'io;
import extensions;
import extensions'routines;
Line 1,250 ⟶ 1,495:
public program()
{
File.assign:("file.txt").forEachLine(printingLn)
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
Two Slightly different solutions in the FileReader namespace
<syntaxhighlight lang="elixir">
<lang Elixir>
defmodule FileReader do
# Create a File.Stream and inspect each line
Line 1,279 ⟶ 1,524:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Erlang}}==
read_a_file_line_by_line:into_list/1 is used by [[Read_a_specific_line_from_a_file]]. If this task is updated keep backwards compatibility, or change [[Read_a_specific_line_from_a_file]], too.
<langsyntaxhighlight lang="erlang">
-module( read_a_file_line_by_line ).
 
Line 1,296 ⟶ 1,541:
into_list( {error, _Error}, _IO, Acc ) -> lists:reverse( Acc );
into_list( Line, IO, Acc ) -> into_list( io:get_line(IO, ''), IO, [Line | Acc] ).
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,311 ⟶ 1,556:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM LETTURA
 
Line 1,333 ⟶ 1,578:
CLOSE(1) ! chiude il file
END PROGRAM
</syntaxhighlight>
</lang>
From ERRE manual: use an EXCEPTION to trap a "file not found" error. If you change INPUT(LINE statement with a GET you can read the file one character at time.
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">constant cmd = command_line()
constant filename = cmd[2]
constant fn = open(filename,"r")
Line 1,351 ⟶ 1,596:
i += 1
end while
close(fn)</langsyntaxhighlight>
 
{{out}}
Line 1,383 ⟶ 1,628:
Wednesday
</pre>
(1) name the euphoria script file <B>readfile.ex</B> andor ifwhatever name you changewant to give it. Change this line "constant filename = cmd[2]" to "constant filename = cmd[<B>3</B>]" and fromlike the command linefollowing run:code.
 
<lang cmd>
<syntaxhighlight lang="euphoria">constant cmd = command_line()
constant filename = cmd[3]
constant fn = open(filename,"r")
integer i
i = 1
object x
while 1 do
x = gets(fn)
if atom(x) then
exit
end if
printf(1,"%2d: %s",{i,x})
i += 1
end while
close(fn)</syntaxhighlight>
 
 
From the command line run:
<syntaxhighlight lang="cmd">
eui readfile.ex "File.txt"
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,401 ⟶ 1,665:
=={{header|F_Sharp|F#}}==
Using DotNet's [http://msdn.microsoft.com/en-us/library/dd383503.aspx System.IO.File.ReadLines] iterator:
<langsyntaxhighlight lang="fsharp">open System.IO
 
[<EntryPoint>]
let main argv =
File.ReadLines(argv.[0]) |> Seq.iter (printfn "%s")
0</langsyntaxhighlight>
 
=={{header|Factor}}==
 
<langsyntaxhighlight lang="factor"> "path/to/file" utf8 [ [ readln dup [ print ] when* ] loop ] with-file-reader</langsyntaxhighlight>
 
=={{header|Fantom}}==
Line 1,416 ⟶ 1,680:
Reads each line from the file "data.txt".
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,427 ⟶ 1,691:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
 
<syntaxhighlight lang="forth">\ The scratch area provided by PAD is always at least 84 characters in
<lang forth>4096 constant max-line
\ length. However, READ-LINE may (but does not have to) read up to
\ two line-terminating characters into the buffer after the line, so
\ the buffer size should always be two larger than the limit given to
\ READ-LINE. Lines that are two long to fit into the buffer will be split,
\ so you can't tell they aren't separate lines.
82 constant max-line
 
: third ( A b c -- A b c A )
>r over r> swap ;
 
: read-lines ( fileid -- fileid )
begin pad max-line third( readfileid pad max-line throw)
while pad swap third ( fileid cpad max-addrline ufileid ) \ string excludes the newline
read-line throw ( fileid chars-read )
2drop
while pad swap ( fileid pad chars-read ) \ string excludes the newline
repeat 2drop ;</lang>
type cr
repeat
\ Get rid of number of characters read by last call to read-line, which is
\ zero because no charaters were read.
drop
;
 
s" infile.txt" r/o open-file throw read-lines close-file throw
</syntaxhighlight>
Given the file
<nowiki>Line 1.
This is some text. It should be longer than the buffer size. That makes it weird, don't you think?
Last line.</nowiki>
the result should be something like this:
<nowiki>$ gforth reading-line-by-line-part-1-variant-2.fs -e bye
Line 1.
This is some text. It should be longer than the buffer size. That makes it weird
, don't you think?
Last line.</nowiki>
 
 
An alternative version that opens a named file, allocates a buffer of the requested size, reads and
prints each line, frees the buffer, and closes the file.
<syntaxhighlight lang="forth">: read-lines' ( filename-addr filename-len -- )
r/o open-file throw ( buffer-len wfileid )
over 2 + \ Add space for up to two line terminators after the buffer.
allocate throw ( buffer-len wfileid buffer-addr )
-rot 2>r ( buffer-addr )
begin
dup 2r@ read-line throw ( buffer bytes-read flag )
while
( buffer-addr bytes-read )
over swap type cr
repeat
drop free throw
2r> close-file throw drop ;
 
4096 s" infile.txt" read-lines'</syntaxhighlight>
 
=={{header|Fortran}}==
Line 1,455 ⟶ 1,763:
 
In the absence of such error reception, ugly messages are presented as the prog. is cancelled, and the most common such error is to name a missing file. So, an INQUIRE statement to check first. This too should have an ERR and IOSTAT blather (the file name might be malformed) but enough is enough. The assignment direction for such codes as EXIST and IOSTAT is ''left'' to right rather than the usual right to left (as in FILE = FNAME), but rather than remember this, it is easiest to take advantage of Fortran's (complete) absence of reserved words and define a logical variable EXIST so that the statement is EXIST = EXIST, and the compiler and the programmer can go their own ways.
<syntaxhighlight lang="fortran">
<lang Fortran>
INTEGER ENUFF !A value has to be specified beforehand,.
PARAMETER (ENUFF = 2468) !Provide some provenance.
Line 1,486 ⟶ 1,794:
20 CLOSE (IN) !All done.
END !That's all.
</syntaxhighlight>
</lang>
With F90 and later it is possible to use an ALLOCATE statement to prepare a variable of a size determined at run time, so that one could for each record use the <code>Q</code> format code (or a new feature of the READ statement) to ascertain the size of the record about to be read, free the storage for the old ALINE and allocate a new sized ALINE, then read that record into ALINE. This avoids worrying about the record overflowing (or underflowing) ALINE, at the cost of hammering at the memory allocation process.
 
Line 1,492 ⟶ 1,800:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Open "input.txt" For Input As #1
Line 1,503 ⟶ 1,811:
Print
Print "Press any key to quit"
Sleep </langsyntaxhighlight>
 
=={{header|Frink}}==
The <CODE>lines</CODE> function can also take an optional second string argument indicating the encoding of the file, and can read from any supported URL type (HTTP, FTP, etc.) or a <CODE>java.io.InputStream</CODE>.
<langsyntaxhighlight lang="frink">
for line = lines["file:yourfile.txt"]
println[line]
</syntaxhighlight>
</lang>
 
=={{header|Gambas}}==
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim hFile As File
Dim sLine As String
Line 1,524 ⟶ 1,832:
Wend
 
End</langsyntaxhighlight>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">ReadByLines := function(name)
local file, line, count;
file := InputTextFile(name);
Line 1,544 ⟶ 1,852:
# With [http://www.ibiblio.org/pub/docs/misc/amnesty.txt amnesty.txt]
ReadByLines("amnesty.txt");
# 384</langsyntaxhighlight>
 
=={{header|Genie}}==
<langsyntaxhighlight lang="genie">[indent=4]
/*
Read file line by line, in Genie
Line 1,569 ⟶ 1,877:
lines++
stdout.printf("%04d %s\n", lines, line)
line = file.read_line()</langsyntaxhighlight>
 
{{out}}
Line 1,587 ⟶ 1,895:
Scanning stops unrecoverably at EOF, the first I/O error, or a token too large to fit in the buffer. When a scan stops, the reader may have advanced arbitrarily far past the last token. Programs that need more control over error handling or large tokens, or must run sequential scans on a reader, should use bufio.Reader instead.
 
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,625 ⟶ 1,933:
}
}
</syntaxhighlight>
</lang>
 
;ReadLine
This function allows files to be rapidly scanned for desired data while minimizing memory allocations. It also handles /r/n line endings and allows unreasonably long lines to be handled as error conditions.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,691 ⟶ 1,999:
fmt.Println(string(line))
}
}</langsyntaxhighlight>
;ReadString
In comparison, ReadString is a little quick and dirty, but is often good enough.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,725 ⟶ 2,033:
}
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">new File("Test.txt").eachLine { line, lineNumber ->
println "processing line $lineNumber: $line"
}</langsyntaxhighlight>
 
 
Line 1,736 ⟶ 2,044:
Thanks to laziness, there's no difference between reading the file all at once and reading it line by line.
 
<langsyntaxhighlight Haskelllang="haskell">main = do
file <- readFile "linebyline.hs"
mapM_ putStrLn (lines file)
</syntaxhighlight>
</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
Line oriented I/O is basic. This program reads lines from "input.txt" into the variable line, but does nothing with it.
 
<langsyntaxhighlight Iconlang="icon">procedure main()
f := open("input.txt","r") | stop("cannot open file ",fn)
while line := read(f)
close(f)
end</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,758 ⟶ 2,066:
This implementation does nothing special when dealing with multi-gigabyte lines. If you encounter an excessively large line and if do not have enough physical memory, your system will experience heavy memory pressure. If you also do not have enough virtual memory to hold a line you will get an out of memory exception.
 
<langsyntaxhighlight lang="j">cocurrent 'linereader'
 
NB. configuration parameter
Line 1,791 ⟶ 2,099:
lines=: }.lines
r
)</langsyntaxhighlight>
 
<langsyntaxhighlight lang="j"> example=: '/tmp/example.txt' conew 'linereader'
next__example''
this is line 1
next__example''
and this is line 2</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.io.BufferedReader;
import java.io.FileReader;
 
Line 1,838 ⟶ 2,146:
}
}
}</langsyntaxhighlight>
{{works with|Java|7+}}
In Java 7, the try with resources block handles multiple readers and writers without nested try blocks. The loop in the main method would look like this:
<langsyntaxhighlight lang="java5">for (String filename : args) {
try (FileReader fr = new FileReader(filename);BufferedReader br = new BufferedReader(fr)){
String line;
Line 1,852 ⟶ 2,160:
x.printStackTrace();
}
}</langsyntaxhighlight>
<code>fr</code> and <code>br</code> are automatically closed when the program exits the try block (it also checks for nulls before closing and throws closing exceptions out of the block).
 
A more under-the-hood method in Java 7 would be to use the <code>Files</code> class (line numbers can be inferred from indices in the returned <code>List</code>):
<langsyntaxhighlight lang="java5">import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.Charset;
Line 1,866 ⟶ 2,174:
}catch(IOException | SecurityException e){
//problem with the file
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">var fs = require("fs");
 
var readFile = function(path) {
Line 1,875 ⟶ 2,183:
};
 
console.log(readFile('file.txt'));</langsyntaxhighlight>
 
=={{header|jq}}==
When invoked with the -R option, jq will read each line as a JSON string. For example:
<langsyntaxhighlight lang="sh">$ seq 0 5 | jq -R 'tonumber|sin'
0
0.8414709848078965
Line 1,885 ⟶ 2,193:
0.1411200080598672
-0.7568024953079282
-0.9589242746631385</langsyntaxhighlight>
 
To perform any kind of reduction operation while reading the lines one-by-one, one would normally use
`input` or `inputs`. For example, to compute the maximum of the above sin values:
 
<langsyntaxhighlight lang="sh">$ seq 0 5 | jq -Rnn '[inputs | tonumber |sin] | max'
0.9092974268256817</langsyntaxhighlight>
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">/* Read by line, in Jsish */
var f = new Channel('read-by-line.jsi');
var line;
 
while (line = f.gets()) puts(line);
f.close();</langsyntaxhighlight>
{{out}}
<pre>prompt$ jsish read-by-line.jsi
Line 1,910 ⟶ 2,218:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">open("input_file","r") do f
for line in eachline(f)
println("read line: ", line)
end
end</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.io.File
Line 1,923 ⟶ 2,231:
fun main(args: Array<String>) {
File("input.txt").forEachLine { println(it) }
}</langsyntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(f) = file('foo.txt')
handle => {#f->close}
#f->forEachLine => {^
#1
'<br>' // note this simply inserts an HTML line break between each line.
^}</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">filedialog "Open","*.txt",file$
if file$="" then end
open file$ for input as #f
Line 1,941 ⟶ 2,249:
print t$
wend
close #f</langsyntaxhighlight>
Mac
<langsyntaxhighlight lang="lb">filedialog "Open","*.txt",file$
if file$="" then end
open file$ for input as #f
Line 1,950 ⟶ 2,258:
print t$
wend
close #f </langsyntaxhighlight>
Unix
<langsyntaxhighlight lang="lb">filedialog "Open","*.txt",file$
if file$="" then end
open file$ for input as #f
Line 1,959 ⟶ 2,267:
print t$
wend
close #f </langsyntaxhighlight>
 
=={{header|Lingo}}==
The following code works fine for text files using 'CRLF' or 'CR only' as line end characters, but unfortunately not for the *nix default 'LF only' (note: Lingo's implementation Director does not run on Linux. It was originally created for ancient Mac OS systems, and later also ported to Windows):
<langsyntaxhighlight lang="lingo">fp = xtra("fileIO").new()
fp.openFile(_movie.path & "input.txt", 1)
fileSize = fp.getLength()
Line 1,973 ⟶ 2,281:
if fp.getPosition()>=fileSize then exit repeat
end repeat
fp.closeFile()</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">command readFileLineByLine
local tFile, tLines, startRead
put "/usr/share/dict/words" into tFile
Line 1,988 ⟶ 2,296:
close file tFile
put tLines
end readFileLineByLine</langsyntaxhighlight>
 
=={{header|Logo}}==
Line 1,995 ⟶ 2,303:
* readword - returns a line as a single word, or an empty list if it reached the end of file
* readrawline - returns a line as a single word, with no characters escaped
<langsyntaxhighlight lang="logo">while [not eof?] [print readline]</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">filename = "input.txt"
fp = io.open( filename, "r" )
 
Line 2,006 ⟶ 2,314:
 
fp:close()
</syntaxhighlight>
</lang>
===Simpler version===
The following achieves the same result as the example above, including implicitly closing the file at the end of the loop.
<syntaxhighlight lang="lua">
<lang Lua>
for line in io.lines("input.txt") do
print(line)
end
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
Line 2,019 ⟶ 2,327:
Documents have Load.Doc statement to load text file. Here we see how we make indexes, and then reopen for input, and move to index, and then load a line.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module checkit {
\\ prepare a file
Line 2,073 ⟶ 2,381:
}
checkit
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">path := "file.txt":
while (true) do
input := readline(path):
if input = 0 then break; end if:
#The line is stored in input
end do:</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">strm=OpenRead["input.txt"];
<lang Mathematica>
strm=OpenRead["input.txt"];
If[strm=!=$Failed,
While[line=!=EndOfFile,
Line 2,091 ⟶ 2,398:
(*Do something*)
]];
Close[strm];</syntaxhighlight>
</lang>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 2,098 ⟶ 2,404:
The function fgetl() read lines from file:
 
<syntaxhighlight lang="matlab">
<lang Matlab>
fid = fopen('foobar.txt','r');
if (fid < 0)
Line 2,108 ⟶ 2,414:
end;
fclose(fid)
end; </langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* Read a file and return a list of all lines */
 
readfile(name) := block(
Line 2,118 ⟶ 2,424:
close(f),
v
)$</langsyntaxhighlight>
 
=={{header|Mercury}}==
Basic version.
<langsyntaxhighlight lang="mercury">:- module read_a_file_line_by_line.
:- interface.
 
Line 2,160 ⟶ 2,466:
ReadLineResult = error(Error),
error(io.error_message(Error))
).</langsyntaxhighlight>
 
Version using a stream fold.
 
<langsyntaxhighlight lang="mercury">:- module read_a_file_line_by_line.
:- interface.
 
Line 2,195 ⟶ 2,501:
process_line(line(Line), !LineCount, !IO) :-
!:LineCount = !.LineCount + 1,
io.format("%d: %s", [i(!.LineCount), s(Line)], !IO).</langsyntaxhighlight>
 
=={{header|Neko}}==
Need to define a growing buffer to handle streaming unknown sizes, 2 to the 29 max, for this one.
 
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
Read a file line by line, in Neko
<doc><pre>Tectonics:
Line 2,255 ⟶ 2,561:
} catch a break;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,276 ⟶ 2,582:
=={{header|NetRexx}}==
=== Using Java <tt>Scanner</tt> ===
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,307 ⟶ 2,613:
 
return fileLines
</syntaxhighlight>
</lang>
 
=== Using Java <tt>Reader</tt> ===
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,356 ⟶ 2,662:
 
return fileLines
</syntaxhighlight>
</lang>
 
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">
<lang NewLISP>
(set 'in-file (open "filename" "read"))
(while (read-line in-file)
(write-line))
(close in-file)</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">for line in lines "input.txt":
echo line</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class ReadFile {
Line 2,386 ⟶ 2,692:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
 
To read an entire file into a string, you can:
<langsyntaxhighlight lang="objc">NSString *path = [NSString stringWithString:@"/usr/share/dict/words"];
NSError *error = nil;
NSString *words = [[NSString alloc] initWithContentsOfFile:path
encoding:NSUTF8StringEncoding error:&error];
</syntaxhighlight>
</lang>
 
Use the UTF-8 encoder on ASCII.
Line 2,401 ⟶ 2,707:
Now to get the individual lines, break down the string:
 
<langsyntaxhighlight lang="objc">NSArray* lines = [words componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let () =
let ic = open_in "input.txt" in
try
Line 2,413 ⟶ 2,719:
done
with End_of_file ->
close_in ic</langsyntaxhighlight>
 
But if we want to write a functional loading function we should remember that the <code>try/with</code> couple breaks the [[tail recursion]]. So we should externalise it outside of the loop in another function:
 
<langsyntaxhighlight lang="ocaml">let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
Line 2,433 ⟶ 2,739:
let lines = read_lines ic in
close_in ic;
(lines)</langsyntaxhighlight>
 
we use it like this:
 
<langsyntaxhighlight lang="ocaml">let () =
let lines = lines_of_file "unixdict.txt" in
List.iter print_endline lines</langsyntaxhighlight>
 
=={{header|OforthOdin}}==
 
<syntaxhighlight lang="odin">package main
<lang Oforth>: readFile(fileName)
| line | File new(fileName) forEach: line [ line println ] ;</lang>
 
import "core:os"
=={{header|OxygenBasic}}==
import "core:fmt"
The core function '''GetFile''' reads the whole file:
import "core:bufio"
<lang oxygenbasic>
import "core:strings"
function getline(string s, sys *i, *el) as string
sys e
e=instr i,s,chr(el)
if e=0 then
el=10
e=instr i,s,chr(el) 'files not using chr 13
end if
if e=0 then e=len s
e++
if el=13 then
if asc(s,e)=10 then e++ 'crlf
end if
function = mid s,i,e-i
i=e
end function
 
main :: proc() {
'=====
f, err := os.open("input.txt")
'TEST:
assert(err == 0, "Could not open file")
'=====
defer os.close(f)
 
r: bufio.Reader
s=getfile "t.txt"
buffer: [1024]byte
i=1
bufio.reader_init_with_buf(&r, {os.stream_from_handle(f)}, buffer[:])
wr=""
defer bufio.reader_destroy(&r)
c=0
 
el=13
for {
do
line, err := bufio.reader_read_string(&r, '\n', context.allocator)
wr = getline s,i,el
if wrerr !="" then exitnil do break
defer delete(line, context.allocator)
'print wr
 
c++
line = strings.trim_right(line, "\r")
end do
fmt.print(line)
print "Line count " c
}
</lang>
}</syntaxhighlight>
 
=={{header|Oforth}}==
 
<syntaxhighlight lang="oforth">: readFile(fileName)
| line | File new(fileName) forEach: line [ line println ] ;</syntaxhighlight>
 
=={{header|PARI/GP}}==
Line 2,487 ⟶ 2,785:
 
Thus the usual way of interacting with files in more than the simple way allowed by <code>read</code> is done by PARI with the usual [[#C|C]] commands:
<langsyntaxhighlight Clang="c">FILE *f = fopen(name, "r");
if (!f) {
pari_err(openfiler, "input", name);
Line 2,493 ⟶ 2,791:
while(fgets(line, MAX_LINELEN, f) != NULL) {
// ...
}</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{Works with|Free Pascal}}
Works for text files. "testin.txt" must exist in directory of program and you must have read/write access. No IO-Checks.
<langsyntaxhighlight lang="pascal">(* Read a text-file line by line *)
program ReadFileByLine;
var
Line 2,516 ⟶ 2,814:
Close(InputFile);
Close(OutputFile)
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
For the simple case of iterating over the lines of a file you can do:
<langsyntaxhighlight lang="perl">open(my $fh, '<', 'foobar.txt')
|| die "Could not open file: $!";
while (<$fh>)
Line 2,528 ⟶ 2,826:
process($_);
}
close $fh;</langsyntaxhighlight>
File encoding can be specified like:
<langsyntaxhighlight lang="perl">open(my $fh, '< :encoding(UTF-8)', 'foobar.txt')
|| die "Could not open file: $!";</langsyntaxhighlight>
The angle bracket operator <code>< ></code> reads a filehandle line by line. (The angle bracket operator can also be used to open and read from files that match a specific pattern, by putting the pattern in the brackets.)
 
Without specifying the variable that each line should be put into, it automatically puts it into <code>$_</code>, which is also conveniently the default argument for many Perl functions. If you wanted to use your own variable, you can do something like this:
<langsyntaxhighlight lang="perl">open(my $fh, '<', 'foobar.txt')
|| die "Could not open file: $!";
while (my $line = <$fh>)
Line 2,542 ⟶ 2,840:
process($line);
}
close $fh;</langsyntaxhighlight>
 
The special use of the angle bracket operator with nothing inside, will read from all files whose names were specified on the command line:
<langsyntaxhighlight lang="perl">while (<>) {
chomp;
process($_);
}</langsyntaxhighlight>
 
As noted in <code>perlop.pod</code> under "I/O Operators", <code>&lt;&gt;</code> opens with the 2-arg <code>open()</code> and so can read from a piped command. This can be convenient but is also very much insecure--a user could supply a file with the name like
 
<langsyntaxhighlight Shelllang="shell">perl myscript.pl 'rm -rf / |'</langsyntaxhighlight>
 
or any other arbitrary command, which will be executed when perl attempts to open a pipe for it. As such, this feature is best reserved for one-liners and is bad practice to use in production code. The same is true for the open(FILEHANDLE, EXPR) form of open as opposed to open(FILEHANDLE, MODE, EXPR). (See <code>perlfunc.pod</code> on the <code>open()</code> function.)
Line 2,559 ⟶ 2,857:
 
The readline function can be used instead of < >:
<langsyntaxhighlight lang="perl">open(my $fh, '<', 'foobar.txt') or die "$!";
while (readline $fh)
{ ... }
Line 2,565 ⟶ 2,863:
while (my $line = readline $fh)
{ ... }
close $fh;</langsyntaxhighlight>
The readline function is the internal function used to implement < >, but can be used directly and is useful for conveying programmer intent in certain situations.
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<lang Phix>constant fn = open(command_line()[2],"r")
<!--<syntaxhighlight lang="phix">-->
integer lno = 1
<span style="color: #008080;">constant</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: #7060A8;">command_line</span><span style="color: #0000FF;">()[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"r"</span><span style="color: #0000FF;">)</span>
object line
<span style="color: #004080;">integer</span> <span style="color: #000000;">lno</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
while 1 do
<span style="color: #004080;">object</span> <span style="color: #000000;">line</span>
line = gets(fn)
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
if atom(line) then exit end if
<span style="color: #000000;">line</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>
printf(1,"%2d: %s",{lno,line})
<span style="color: #008080;">if</span> <span style="color: #004080;">atom</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
lno += 1
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2d: %s"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">lno</span><span style="color: #0000FF;">,</span><span style="color: #000000;">line</span><span style="color: #0000FF;">})</span>
end while
<span style="color: #000000;">lno</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
close(fn)
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
{} = wait_key()</lang>
<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: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,596 ⟶ 2,897:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
argument 1 get "r" fopen var f>ps
 
true
while
ftps fgets number? if drop fps> fclose false else print true endif
endwhile</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$file = fopen(__FILE__, 'r'); // read current file
while ($line = fgets($file)) {
$line = rtrim($line); // removes linebreaks and spaces at end
echo strrev($line) . "\n"; // reverse line and upload it
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="php"><?php // HOW TO ECHO FILE LINE BY LINE FROM THE COMMAND LINE: php5-cli
$file = fopen('test.txt', 'r'); // OPEN FILE WITH READ ACCESS
while (!feof($file)) {
$line = rtrim(fgets($file)); // REMOVE TRAILING WHITESPACE AND GET LINE
if($line != NULL) echo("$line\n"); // IF THE LINE ISN'T NULL, ECHO THE LINE
}</langsyntaxhighlight>
 
=={{header|Picat}}==
 
===read_line/1===
The proper way of reading a file line by line is to use <code>read_line(FH)</code>. This is he recommended way for a very large files.
<syntaxhighlight lang="picat">go =>
FD = open("unixdict.txt"),
while (not at_end_of_stream(FD))
Line = read_line(FD),
println(Line)
end,
close(FD),
nl.</syntaxhighlight>
 
===read_file_lines===
For reasonable sized files, <code>read_file_lines/1</code> is usually the way to go.
<syntaxhighlight lang="picat">go2 =>
foreach(Line in read_file_lines("unixdict.txt"))
println(Line)
end.</syntaxhighlight>
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(in "foobar.txt"
(while (line)
(process @) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">
read: procedure options (main);
declare line character (500) varying;
Line 2,636 ⟶ 2,958:
end;
end read;
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">$reader = [System.IO.File]::OpenText($mancorfile)
try {
do {
Line 2,649 ⟶ 2,971:
$reader.Close()
}
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">FileName$ = OpenFileRequester("","foo.txt","*.txt",0)
 
If ReadFile(0, FileName$) ; use ReadFile instead of OpenFile to include read-only files
Line 2,661 ⟶ 2,983:
Wend
CloseFile(0)
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
For the simple case of iterating over the lines of a file you can do:
<langsyntaxhighlight lang="python">with open("foobar.txt") as f:
for line in f:
process(line)</langsyntaxhighlight>
The with statement ensures the correct closing of the file after it is processed, and iterating over the file object <code>f</code>, adjusts what is considered line separator character(s) so the code will work on multiple operating systems such as Windows, Mac, and Solaris without change.<br>
Any exceptional conditions seen when processing the file will raise an exception. Leaving the while loop because of an exception will also cause the file to be correctly closed on the way.
 
Python also has the [http://docs.python.org/library/fileinput.html fileinput module]. This can process multiple files parsed from the command line and can be set to modify files 'in-place'.
<langsyntaxhighlight lang="python">import fileinput
for line in fileinput.input():
process(line)
</syntaxhighlight>
</lang>
 
=={{header|R}}==
 
<langsyntaxhighlight Rlang="r">conn <- file("notes.txt", "r")
while(length(line <- readLines(conn, 1)) > 0) {
cat(line, "\n")
}</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">(define (read-next-line-iter file)
(let ((line (read-line file 'any)))
(unless (eof-object? line)
Line 2,691 ⟶ 3,013:
(newline)
(read-next-line-iter file))))
(call-with-input-file "foobar.txt" read-next-line-iter)</langsyntaxhighlight>
 
<langsyntaxhighlight lang="racket">(define in (open-input-file file-name))
(for ([line (in-lines in)])
(displayln line))
(close-input-port in)</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
The lines method is lazy so the following code does indeed read the file line by line, and not all at once.
<syntaxhighlight lang="raku" perl6line>for open('test.txt').lines
{
.say
}</langsyntaxhighlight>
 
In order to be more explicit about the file being read on line at a time, one can write:
<syntaxhighlight lang="raku" perl6line>my $f = open 'test.txt';
while my $line = $f.get {
say $line;
}</langsyntaxhighlight>
 
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
<lang vb>
$Include "Rapidq.inc"
dim file as qfilestream
Line 2,726 ⟶ 3,048:
 
input "Press enter to exit: ";a$
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
Line 2,734 ⟶ 3,056:
<br>beginning of the file needs to be re-established so the reading can start from the beginning of the file.
<br><br>The &nbsp; '''lineout''' &nbsp; BIF closes the file (in most REXX interpreters); &nbsp; this is done for general housekeeping.
<langsyntaxhighlight lang="rexx">/*REXX program reads and displays (with a count) a file, one line at a time. */
parse arg fID . /*obtain optional argument from the CL.*/
if fID=='' then exit 8 /*Was no fileID specified? Then quit. */
Line 2,746 ⟶ 3,068:
say /*stick a fork in it, we're all done. */
say center(' file ' fID " has " #-1 ' records.', 79, '═') /*show rec count. */
call lineout fID /*close the input file (most REXXes). */</langsyntaxhighlight><br><br>
 
=== deluxe version ===
Line 2,754 ⟶ 3,076:
<br>It can also just show the last line.
<br>If appropriate, the program will show the total number of lines in the file.
 
<lang rexx></lang>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 123456.TXT </tt>}}
<pre>
Line 2,833 ⟶ 3,155:
 
=== ARexx version ===
<langsyntaxhighlight lang="rexx">/* Also works with Regina if you state OPTIONS AREXX_BIFS ; OPTIONS AREXX_SEMANTICS */
filename='file.txt'
contents=''
Line 2,844 ⟶ 3,166:
ELSE EXIT 20
CALL Close filehandle
EXIT 0</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
fp = fopen("C:\Ring\ReadMe.txt","r")
r = ""
Line 2,856 ⟶ 3,178:
end
fclose(fp)
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">IO.foreach "foobar.txt" do |line|
# Do something with line.
puts line
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ruby"># File inherits from IO, so File.foreach also works.
File.foreach("foobar.txt") {|line| puts line}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ruby"># IO.foreach and File.foreach can also read a subprocess.
IO.foreach "| grep afs3 /etc/services" do |line|
puts line
end</langsyntaxhighlight>
 
''Caution!'' IO.foreach and File.foreach take a portname.
Line 2,877 ⟶ 3,199:
The block form of File.open automatically closes the file after running the block.
 
<langsyntaxhighlight lang="ruby">filename = "|strange-name.txt"
File.open(filename) do |file|
file.each {|line| puts line}
end</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">open DefaultDir$ + "\public\filetest.txt" for input as #f
while not(eof(#f))
line input #f, a$
Line 2,889 ⟶ 3,211:
wend
close #f
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::io::{BufReader,BufRead};
use std::fs::File;
 
Line 2,900 ⟶ 3,222:
println!("{}", line.unwrap());
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,908 ⟶ 3,230:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import scala.io._
Source.fromFile("foobar.txt").getLines.foreach(println)</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">; Commented line below should be uncommented to use read-line with Guile
;(use-modules (ice-9 rdelim))
 
Line 2,918 ⟶ 3,240:
(do ((line (read-line file) (read-line file))) ((eof-object? line))
(display line)
(newline))</langsyntaxhighlight>
 
=={{header|Sed}}==
Through a .sed file:
<langsyntaxhighlight lang="sed">#!/bin/sed -f
p
</syntaxhighlight>
</lang>
 
or through a one-liner in bash:
<langsyntaxhighlight lang="bash">
sed p filename
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 2,944 ⟶ 3,266:
writeln("LINE: " <& line);
end while;
end func;</langsyntaxhighlight>
 
The function [http://seed7.sourceforge.net/libraries/file.htm#hasNext%28in_file%29 hasNext]
Line 2,950 ⟶ 3,272:
 
=={{header|SenseTalk}}==
The simple way:
<lang sensetalk>put "input.txt" into myFile
<syntaxhighlight lang="sensetalk">repeat with each line of file "input.txt"
put it
end repeat
</syntaxhighlight>
 
The more traditional way:
<syntaxhighlight lang="sensetalk">put "input.txt" into myFile
open file myFile
 
Line 2,959 ⟶ 3,288:
end repeat
 
close file myFile</langsyntaxhighlight>
 
=={{header|Sidef}}==
''FileHandle.each{}'' is lazy, allowing us to do this:
<langsyntaxhighlight lang="ruby">File(__FILE__).open_r.each { |line|
printsay line
}</langsyntaxhighlight>
 
Same thing explicitly:
<langsyntaxhighlight lang="ruby">var fh = File(__FILE__).open_r
while (fh.readline(\var line)) {
printsay line
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|Pharo}}
<langsyntaxhighlight lang="smalltalk">
(StandardFileStream oldFileNamed: 'test.txt') contents lines do: [ :each | Transcript show: each. ]
</syntaxhighlight>
</lang>
 
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">'foobar.txt' asFilename readingLinesDo:[:eachLine | eachLine printCR]</langsyntaxhighlight>
alternatively:
<langsyntaxhighlight lang="smalltalk">|s|
s := 'foobar.txt' asFilename readStream.
[ s atEnd ] whileFalse:[
s nextLine printCR.
].
s close</langsyntaxhighlight>
alternatively:
<langsyntaxhighlight lang="smalltalk">'foobar.txt' asFilename contents do:[:eachLine | eachLine printCR].</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
Line 3,000 ⟶ 3,329:
Accessing the variable fails (does not succeed) when the end of file is reached.
 
<langsyntaxhighlight lang="snobol4"> input(.infile,20,"readfrom.txt") :f(end)
rdloop output = infile :s(rdloop)
end</langsyntaxhighlight>
 
=={{header|Sparkling}}==
<langsyntaxhighlight lang="sparkling">let f = fopen("foo.txt", "r");
if f != nil {
var line;
Line 3,013 ⟶ 3,342:
 
fclose(f);
}</langsyntaxhighlight>
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">f = "file.txt"
> !#.eof(f)
#.output(#.readline(f))
<</langsyntaxhighlight>
 
=={{header|Standard ML}}==
Gets the lines of a file as a list of strings with trailing newline removed.
 
<syntaxhighlight lang="sml">fun readLines string =
let
val strm = TextIO.openIn path
fun chomp str =
let
val xstr = String.explode str
val slen = List.length xstr
in
String.implode(List.take(xstr, (slen-1)))
end
fun collectLines ls s =
case TextIO.inputLine s of
SOME(l) => collectLines (chomp l::ls) s
| NONE => ls
in
List.rev (collectLines [] strm) before TextIO.closeIn strm
end
</syntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set f [open "foobar.txt"]
while {[gets $f line] >= 0} {
# This loops over every line
puts ">>$line<<"
}
close $f</langsyntaxhighlight>
 
=={{header|TorqueScript}}==
Line 3,033 ⟶ 3,384:
Read a file line by line:
 
<syntaxhighlight lang="torquescript">
<lang TorqueScript>
//Create a file object
 
Line 3,056 ⟶ 3,407:
 
%f.delete();
</syntaxhighlight>
</lang>
 
=={{header|Turing}}==
For a named file:
<langsyntaxhighlight lang="turing">var f : int
open : f, "rosetta.txt", get
loop
Line 3,068 ⟶ 3,419:
put line
end loop
close : f</langsyntaxhighlight>
 
For a command line argument file (e.g. program.x rosetta.txt):
<langsyntaxhighlight lang="turing">loop
exit when eof (1)
var line: string
get : 1, line:*
put line
end loop</langsyntaxhighlight>
 
For standard input (e.g., program.x < rosetta.txt):
<langsyntaxhighlight lang="turing">loop
exit when eof
var line : string
get line:*
put line
end loop</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
 
Line 3,099 ⟶ 3,450:
ENDLOOP
ENDACCESS q
</syntaxhighlight>
</lang>
or:
<langsyntaxhighlight lang="tuscript">
LOOP line=datei
PRINT line
ENDLOOP
</syntaxhighlight>
</lang>
 
 
Line 3,111 ⟶ 3,462:
Taken from C++ U++ section
 
<langsyntaxhighlight lang="cpp">#include <Core/Core.h>
 
using namespace Upp;
Line 3,120 ⟶ 3,471:
while(in && !in.IsEof())
Cout().PutLine(in.GetLine());
}</langsyntaxhighlight>
 
 
Line 3,130 ⟶ 3,481:
{{works with|Almquist Shell}}
 
<langsyntaxhighlight lang="bash"># This while loop repeats for each line of the file.
# This loop is inside a pipeline; many shells will
# run this loop inside a subshell.
Line 3,136 ⟶ 3,487:
while IFS= read -r line ; do
printf '%s\n' "$line"
done</langsyntaxhighlight>
 
{{works with|Almquist Shell}}
 
<langsyntaxhighlight lang="bash"># This loop runs in the current shell, and can read both
# the old standard input (fd 1) and input.txt (fd 3).
exec 3<input.txt
Line 3,146 ⟶ 3,497:
printf '%s\n' "$line"
done
exec 3>&-</langsyntaxhighlight>
 
{{works with|Bourne Shell}}
 
<langsyntaxhighlight lang="bash"># The old Bourne Shell interprets 'IFS= read' as 'IFS= ; read'.
# It requires extra code to restore the original value of IFS.
exec 3<input.txt
Line 3,159 ⟶ 3,510:
done
IFS=$oldifs
exec 3>&-</langsyntaxhighlight>
 
=={{header|Ursa}}==
Reads the file "filename.txt" and outputs it to the console line by line.
<langsyntaxhighlight lang="ursa">decl file f
f.open "filename.txt"
while (f.hasline)
out (in string f) endl console
end while</langsyntaxhighlight>
 
=={{header|Vala}}==
Reads and prints out file line by line:
<langsyntaxhighlight lang="vala">
public static void main(){
var file = FileStream.open("foo.txt", "r");
Line 3,181 ⟶ 3,532:
}
}
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">' Read a file line by line
Sub Main()
Dim fInput As String, fOutput As String 'File names
Line 3,199 ⟶ 3,550:
Close #1
Close #2
End Sub 'Main</langsyntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
FilePath = "<SPECIFY FILE PATH HERE>"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Line 3,211 ⟶ 3,562:
objFile.Close
Set objFSO = Nothing
</syntaxhighlight>
</lang>
 
=={{header|Vedit macro language}}==
Line 3,220 ⟶ 3,571:
This example reads the source code of this macro,
copies it line by line into a new buffer and adds line numbers.
<langsyntaxhighlight lang="vedit">File_Open("line_by_line.vdm")
#10 = Buf_Num // edit buffer for input file
#11 = Buf_Free // edit buffer for output
Line 3,234 ⟶ 3,585:
}
Buf_Close(NOMSG) // close the input file
Buf_Switch(#11) // show the output </langsyntaxhighlight>
 
{{out}}
Line 3,259 ⟶ 3,610:
===Simple version===
{{works with|Visual Basic|VB6 Standard}}
<langsyntaxhighlight lang="vb">' Read a file line by line
Sub Main()
Dim fInput As String, fOutput As String 'File names
Line 3,282 ⟶ 3,633:
InputError:
MsgBox "File: " & fInput & " not found"
End Sub 'Main</langsyntaxhighlight>
 
===Complex version===
<langsyntaxhighlight lang="vb">' Read lines from a file
'
' (c) Copyright 1993 - 2011 Mark Hobley
Line 3,417 ⟶ 3,768:
Public Function btrim$(arg$)
btrim$ = LTrim$(RTrim$(arg$))
End Function</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Imports System.IO
 
' Loop through the lines of a file.
Line 3,436 ⟶ 3,787:
oReader.Close()
 
End Sub</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
import os
 
fn main() {
file := './file.txt'
mut content_arr := []string{}
if os.is_file(file) == true {
content_arr << os.read_lines(file) or {
println('Error: can not read')
exit(1)
}
}
else {
println('Error: can not find file')
exit(1)
}
 
for content in content_arr {
if content !='' {
println(content)
}
}
}
</syntaxhighlight>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="wart">with infile "x"
drain (read_line)</langsyntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">import "io" for File
 
var lines = [] // store lines read
Line 3,465 ⟶ 3,843:
}
 
System.print(lines.join("\n")) // print out lines</langsyntaxhighlight>
 
=={{header|XPL0}}==
File is redirected on command line i.e: <file.txt
<langsyntaxhighlight XPL0lang="xpl0">int C;
[repeat repeat C:= ChIn(1); \repeat until end-of-line
ChOut(0, C);
until C < $20; \CR, LF, or EOF
until C = \EOF\ $1A; \repeat until end-of-file
]</langsyntaxhighlight>
 
=={{header|zkl}}==
So many ways, here are a few
<langsyntaxhighlight lang="zkl">foreach line in (File("foo.zkl")){print(line)}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">File("foo.zkl").pump(Console.print)</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">Utils.zipWith(False,fcn(a,b){"%d: %s".fmt(a,b).print()},
[0..],File("foo.zkl","r"))
-->
0: var R; n:=GarbageMan.gcCount;
1: ref := GarbageMan.WeakRef(String("the","quick brown fox"));
...</langsyntaxhighlight>
23

edits