Input loop: Difference between revisions

Content added Content deleted
(Added NodeJS and Typescript)
m (syntax highlighting fixup automation)
Line 15: Line 15:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program inputLoop64.s */
/* program inputLoop64.s */
Line 176: Line 176:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC ReadStream(BYTE stream)
<syntaxhighlight lang="action!">PROC ReadStream(BYTE stream)
CHAR ARRAY line(255)
CHAR ARRAY line(255)


Line 197: Line 197:
ReadStream(streamId)
ReadStream(streamId)
Close(streamId)
Close(streamId)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Input_loop.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Input_loop.png Screenshot from Atari 8-bit computer]
Line 227: Line 227:
This example reads in a text stream from standard input line by line
This example reads in a text stream from standard input line by line
and writes the output to standard output.
and writes the output to standard output.
<lang ada>with Ada.Text_Io; use Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;


procedure Read_Stream is
procedure Read_Stream is
Line 244: Line 244:
end if;
end if;
end loop;
end loop;
end Read_Stream;</lang>
end Read_Stream;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>void
<syntaxhighlight lang="aime">void
read_stream(file f)
read_stream(file f)
{
{
Line 255: Line 255:
# the read line available as -s-
# the read line available as -s-
}
}
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
For file consisting of just one page - a typical linux/unix file:
For file consisting of just one page - a typical linux/unix file:
<lang algol68>main:(
<syntaxhighlight lang="algol68">main:(
PROC raise logical file end = (REF FILE f) BOOL: ( except logical file end );
PROC raise logical file end = (REF FILE f) BOOL: ( except logical file end );
on logical file end(stand in, raise logical file end);
on logical file end(stand in, raise logical file end);
Line 269: Line 269:
except logical file end:
except logical file end:
SKIP
SKIP
)</lang>
)</syntaxhighlight>
For multi page files, each page is seekable with ''<tt>PROC set = (REF FILE file, INT page, line, char)VOID: ~</tt>''. This allows rudimentary random access where each new page is effectively a new record.
For multi page files, each page is seekable with ''<tt>PROC set = (REF FILE file, INT page, line, char)VOID: ~</tt>''. This allows rudimentary random access where each new page is effectively a new record.
<lang algol68>main:(
<syntaxhighlight lang="algol68">main:(
PROC raise logical file end = (REF FILE f) BOOL: ( except logical file end );
PROC raise logical file end = (REF FILE f) BOOL: ( except logical file end );
on logical file end(stand in, raise logical file end);
on logical file end(stand in, raise logical file end);
Line 288: Line 288:
except logical file end:
except logical file end:
SKIP
SKIP
)</lang>
)</syntaxhighlight>
The boolean functions ''physical file ended(f)'', ''logical file ended(f)'', ''page ended(f)'' and ''line ended(f)'' are also available to indicate the end of a file, page and line.
The boolean functions ''physical file ended(f)'', ''logical file ended(f)'', ''page ended(f)'' and ''line ended(f)'' are also available to indicate the end of a file, page and line.


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
string(80) line;
string(80) line;
% allow the program to continue after reaching end-of-file %
% allow the program to continue after reaching end-of-file %
Line 303: Line 303:
read( line )
read( line )
end
end
end.</lang>
end.</syntaxhighlight>


=={{header|AmigaE}}==
=={{header|AmigaE}}==
<lang amigae>CONST BUFLEN=1024, EOF=-1
<syntaxhighlight lang="amigae">CONST BUFLEN=1024, EOF=-1


PROC consume_input(fh)
PROC consume_input(fh)
Line 331: Line 331:
Close(fh)
Close(fh)
ENDIF
ENDIF
ENDPROC</lang>
ENDPROC</syntaxhighlight>


=={{header|APL}}==
=={{header|APL}}==
{{works with|GNU APL}}
{{works with|GNU APL}}
<syntaxhighlight lang="apl">
<lang APL>
h ← ⊃ (⎕fio['read_text'] 'corpus/sample1.txt')
h ← ⊃ (⎕fio['read_text'] 'corpus/sample1.txt')
⍴h
⍴h
Line 350: Line 350:
│ │
│ │
└─────────────────────────────────────────────────┘
└─────────────────────────────────────────────────┘
</syntaxhighlight>
</lang>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 502: Line 502:
/***************************************************/
/***************************************************/
.include "../affichage.inc"
.include "../affichage.inc"
</syntaxhighlight>
</lang>
{{Output}}
{{Output}}
<pre>
<pre>
Line 523: Line 523:
This example reads the text of a source file line by line
This example reads the text of a source file line by line
and writes the output to a destination file.
and writes the output to a destination file.
<lang AutoHotkey>Loop, Read, Input.txt, Output.txt
<syntaxhighlight lang="autohotkey">Loop, Read, Input.txt, Output.txt
{
{
FileAppend, %A_LoopReadLine%`n
FileAppend, %A_LoopReadLine%`n
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
This just reads lines from stdin and prints them until EOF is read.
This just reads lines from stdin and prints them until EOF is read.


<lang awk>{ print $0 }</lang>
<syntaxhighlight lang="awk">{ print $0 }</syntaxhighlight>


or, more idiomatic:
or, more idiomatic:


<lang awk>1</lang>
<syntaxhighlight lang="awk">1</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang BASIC256>f = freefile
<syntaxhighlight lang="basic256">f = freefile
open f, "test.txt"
open f, "test.txt"


Line 547: Line 547:
end while
end while
close f
close f
end</lang>
end</syntaxhighlight>


==={{header|OxygenBasic}}===
==={{header|OxygenBasic}}===
<lang>
<syntaxhighlight lang="text">
uses Console
uses Console
uses ParseUtil
uses ParseUtil
Line 560: Line 560:
wend
wend
pause
pause
</syntaxhighlight>
</lang>


==={{header|QBasic}}===
==={{header|QBasic}}===
{{works with|QBasic}}
{{works with|QBasic}}
{{works with|QuickBasic}}
{{works with|QuickBasic}}
<lang QBasic>OPEN "test.txt" FOR INPUT AS #1
<syntaxhighlight lang="qbasic">OPEN "test.txt" FOR INPUT AS #1


WHILE NOT EOF(1)
WHILE NOT EOF(1)
Line 573: Line 573:


CLOSE #1
CLOSE #1
END</lang>
END</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<lang qbasic>OPEN #1: NAME "test.txt", ACCESS INPUT
<syntaxhighlight lang="qbasic">OPEN #1: NAME "test.txt", ACCESS INPUT


DO
DO
Line 584: Line 584:


CLOSE #1
CLOSE #1
END</lang>
END</syntaxhighlight>


==={{header|Yabasic}}===
==={{header|Yabasic}}===
<lang yabasic>filename$ = "test.txt"
<syntaxhighlight lang="yabasic">filename$ = "test.txt"
f = open(filename$)
f = open(filename$)


Line 597: Line 597:


close f
close f
end</lang>
end</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang ApplesoftBasic>100 INPUT "FILENAME:";F$
<syntaxhighlight lang="applesoftbasic">100 INPUT "FILENAME:";F$
110 D$ = CHR$(4)
110 D$ = CHR$(4)
120 PRINT D$"VERIFY"F$
120 PRINT D$"VERIFY"F$
Line 613: Line 613:
190 POKE 216,0
190 POKE 216,0
200 IF PEEK(222) <> 5 THEN RESUME
200 IF PEEK(222) <> 5 THEN RESUME
210 PRINT D$"CLOSE"F$</lang>
210 PRINT D$"CLOSE"F$</syntaxhighlight>


==={{header|BaCon}}===
==={{header|BaCon}}===


<lang freebasic>
<syntaxhighlight lang="freebasic">
'--- some generic header file to give it a real test
'--- some generic header file to give it a real test
PRINT "Enter any file name you want to read ex: /usr/include/X11/X.h"
PRINT "Enter any file name you want to read ex: /usr/include/X11/X.h"
Line 631: Line 631:
INCR i
INCR i
WEND
WEND
</lang>
</syntaxhighlight>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
This specifically relates to console input (stdin).
This specifically relates to console input (stdin).
<lang bbcbasic> STD_INPUT_HANDLE = -10
<syntaxhighlight lang="bbcbasic"> STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_OUTPUT_HANDLE = -11
SYS "GetStdHandle", STD_INPUT_HANDLE TO @hfile%(1)
SYS "GetStdHandle", STD_INPUT_HANDLE TO @hfile%(1)
Line 646: Line 646:
INPUT A$
INPUT A$
PRINT A$
PRINT A$
UNTIL FALSE</lang>
UNTIL FALSE</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
This example should generally work across all Commodore models. It is important to note that when using the reserved variable STATUS (or ST for short) to detect the end of file marker (bit 6), the KERNAL updates this variable based on ''any'' previous I/O operation, including the OPEN command, but makes no indication as to which I/O access the status applies to. Therefore, if using the disk drive, it is best to open the command file number and channel (15) ''before'' opening the actual file on disk, and leave the command channel open while performing the operations to open the file and access it as shown in the example.
This example should generally work across all Commodore models. It is important to note that when using the reserved variable STATUS (or ST for short) to detect the end of file marker (bit 6), the KERNAL updates this variable based on ''any'' previous I/O operation, including the OPEN command, but makes no indication as to which I/O access the status applies to. Therefore, if using the disk drive, it is best to open the command file number and channel (15) ''before'' opening the actual file on disk, and leave the command channel open while performing the operations to open the file and access it as shown in the example.


<syntaxhighlight lang="commodorebasicv2">
<lang CommodoreBASICv2>
10 rem input loop - rosetta code
10 rem input loop - rosetta code
11 rem open command channel, clear screen, switch to lower case
11 rem open command channel, clear screen, switch to lower case
Line 677: Line 677:
1110 print:print er;"- ";er$;" track:";tk;"sector:";sc
1110 print:print er;"- ";er$;" track:";tk;"sector:";sc
1120 return
1120 return
</syntaxhighlight>
</lang>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 PROGRAM "Type.bas"
<syntaxhighlight lang="is-basic">100 PROGRAM "Type.bas"
110 TEXT 80
110 TEXT 80
120 INPUT PROMPT "File name: ":F$
120 INPUT PROMPT "File name: ":F$
Line 694: Line 694:
220 PRINT EXSTRING$(EXTYPE)
220 PRINT EXSTRING$(EXTYPE)
230 END
230 END
240 END HANDLER</lang>
240 END HANDLER</syntaxhighlight>


Alternate solution:
Alternate solution:
<lang IS-BASIC>100 PROGRAM "Type.bas"
<syntaxhighlight lang="is-basic">100 PROGRAM "Type.bas"
110 INPUT PROMPT "File name: ":F$
110 INPUT PROMPT "File name: ":F$
120 WHEN EXCEPTION USE IOERROR
120 WHEN EXCEPTION USE IOERROR
Line 707: Line 707:
180 PRINT EXSTRING$(EXTYPE)
180 PRINT EXSTRING$(EXTYPE)
190 CLOSE #1
190 CLOSE #1
200 END HANDLER</lang>
200 END HANDLER</syntaxhighlight>
==={{header|uBasic/4tH}}===
==={{header|uBasic/4tH}}===
<lang>If Set (a, Open ("myfile.bas", "r")) < 0 Then Print "Cannot open \qmyfile.bas\q" : End
<syntaxhighlight lang="text">If Set (a, Open ("myfile.bas", "r")) < 0 Then Print "Cannot open \qmyfile.bas\q" : End


Do While Read (a)
Do While Read (a)
Line 716: Line 716:


Close a
Close a
</syntaxhighlight>
</lang>
This version tokenizes the line read and prints all individual words.
This version tokenizes the line read and prints all individual words.
<lang>If Set (a, Open ("myfile.bas", "r")) < 0 Then Print "Cannot open \qmyfile.bas\q" : End
<syntaxhighlight lang="text">If Set (a, Open ("myfile.bas", "r")) < 0 Then Print "Cannot open \qmyfile.bas\q" : End


Do While Read (a) ' get next line
Do While Read (a) ' get next line
Line 730: Line 730:


Close a
Close a
</syntaxhighlight>
</lang>


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>
<syntaxhighlight lang="dos">
for /f %%i in (file.txt) do if %%i@ neq @ echo %%i
for /f %%i in (file.txt) do if %%i@ neq @ echo %%i
</syntaxhighlight>
</lang>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
This example first creates a test file with three lines. It then opens the file in read mode, sets the string of break characters and then reads the file token by token, where tokens are delimeted by break characters. Finally, the file position is set to an invalid value, which closes the file.
This example first creates a test file with three lines. It then opens the file in read mode, sets the string of break characters and then reads the file token by token, where tokens are delimeted by break characters. Finally, the file position is set to an invalid value, which closes the file.
<lang bracmat>( put$("This is
<syntaxhighlight lang="bracmat">( put$("This is
a three line
a three line
text","test.txt",NEW)
text","test.txt",NEW)
Line 765: Line 765:
)
)
& (fil$(,SET,-1)|out$"file closed")
& (fil$(,SET,-1)|out$"file closed")
);</lang>
);</syntaxhighlight>
{{out}}
{{out}}
<pre>breakchar:SP, word 1:This
<pre>breakchar:SP, word 1:This
Line 778: Line 778:
Reads arbitrarily long line each time and return a null-terminated string.
Reads arbitrarily long line each time and return a null-terminated string.
Caller is responsible for freeing the string.
Caller is responsible for freeing the string.
<lang c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>


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


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


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.IO;
using System.IO;


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


=={{header|C++}}==
=={{header|C++}}==
The following functions send the words resp. lines
The following functions send the words resp. lines
to a generic output iterator.
to a generic output iterator.
<lang cpp>
<syntaxhighlight lang="cpp">
#include <istream>
#include <istream>
#include <string>
#include <string>
Line 880: Line 880:
}
}


</syntaxhighlight>
</lang>


An alternate way to read words or lines is to use istream iterators:
An alternate way to read words or lines is to use istream iterators:


<lang cpp>
<syntaxhighlight lang="cpp">
template<class OutIt>
template<class OutIt>
void read_words(std::istream& is, OutIt dest)
void read_words(std::istream& is, OutIt dest)
Line 911: Line 911:
dest);
dest);
}
}
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(defn basic-input [fname]
<syntaxhighlight lang="lisp">(defn basic-input [fname]
(line-seq (java.io.BufferedReader. (java.io.FileReader. fname))))</lang>
(line-seq (java.io.BufferedReader. (java.io.FileReader. fname))))</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
{{works with|GNU Cobol|2.0}}
{{works with|GNU Cobol|2.0}}
{{works with|Visual COBOL}}
{{works with|Visual COBOL}}
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. input-loop.
PROGRAM-ID. input-loop.
Line 952: Line 952:
CLOSE in-stream
CLOSE in-stream
.
.
END PROGRAM input-loop.</lang>
END PROGRAM input-loop.</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun basic-input (filename)
<syntaxhighlight lang="lisp">(defun basic-input (filename)
(with-open-file (stream (make-pathname :name filename) :direction :input)
(with-open-file (stream (make-pathname :name filename) :direction :input)
(loop for line = (read-line stream nil nil)
(loop for line = (read-line stream nil nil)
while line
while line
do (format t "~a~%" line))))</lang>
do (format t "~a~%" line))))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio;
import std.stdio;


Line 984: Line 984:
line.writeln;
line.writeln;
}
}
}</lang>
}</syntaxhighlight>


{{libheader|Tango}}
{{libheader|Tango}}
<lang d>import tango.io.Console;
<syntaxhighlight lang="d">import tango.io.Console;
import tango.text.stream.LineIterator;
import tango.text.stream.LineIterator;


Line 994: Line 994:
// do something with each line
// do something with each line
}
}
}</lang>
}</syntaxhighlight>
{{libheader|Tango}}
{{libheader|Tango}}
<lang d>import tango.io.Console;
<syntaxhighlight lang="d">import tango.io.Console;
import tango.text.stream.SimpleIterator;
import tango.text.stream.SimpleIterator;


Line 1,003: Line 1,003:
// do something with each word
// do something with each word
}
}
}</lang>
}</syntaxhighlight>


Note that foreach variables 'line' and 'word' are transient slices. If you need to retain them for later use, you should .dup them.
Note that foreach variables 'line' and 'word' are transient slices. If you need to retain them for later use, you should .dup them.


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program InputLoop;
<syntaxhighlight lang="delphi">program InputLoop;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,024: Line 1,024:
lReader.Free;
lReader.Free;
end;
end;
end.</lang>
end.</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>while /= :eof dup !read-line!stdin:
<syntaxhighlight lang="dejavu">while /= :eof dup !read-line!stdin:
!print( "Read a line: " !decode!utf-8 swap )
!print( "Read a line: " !decode!utf-8 swap )
drop
drop
!print "End of file."</lang>
!print "End of file."</syntaxhighlight>


=={{header|EasyLang}}==
=={{header|EasyLang}}==


<lang>repeat
<syntaxhighlight lang="text">repeat
l$ = input
l$ = input
until error = 1
until error = 1
print l$
print l$
.</lang>
.</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
{{works with|Eiffel Studio|6.6}}
{{works with|Eiffel Studio|6.6}}


<syntaxhighlight lang="eiffel">
<lang Eiffel>
note
note
description : "{
description : "{
Line 1,280: Line 1,280:


end
end
</syntaxhighlight>
</lang>


=={{header|Elena}}==
=={{header|Elena}}==
Line 1,286: Line 1,286:


Using ReaderEnumerator
Using ReaderEnumerator
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import system'io;
import system'io;
import extensions'routines;
import extensions'routines;
Line 1,293: Line 1,293:
{
{
ReaderEnumerator.new(File.assign:"file.txt").forEach(printingLn)
ReaderEnumerator.new(File.assign:"file.txt").forEach(printingLn)
}</lang>
}</syntaxhighlight>
Using loop statement
Using loop statement
<lang elena>import system'io;
<syntaxhighlight lang="elena">import system'io;
public program()
public program()
Line 1,306: Line 1,306:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
def input_loop(stream) do
def input_loop(stream) do
case IO.read(stream, :line) do
case IO.read(stream, :line) do
Line 1,320: Line 1,320:


path = hd(System.argv)
path = hd(System.argv)
File.open!(path, [:read], fn stream -> RC.input_loop(stream) end)</lang>
File.open!(path, [:read], fn stream -> RC.input_loop(stream) end)</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>% Implemented by Arjun Sunel
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(read_files).
-module(read_files).
-export([main/0]).
-export([main/0]).
Line 1,331: Line 1,331:
Lines = string:tokens(binary_to_list(Read("read_files.erl")), "\n"),
Lines = string:tokens(binary_to_list(Read("read_files.erl")), "\n"),
lists:foreach(fun (Y) -> io:format("~s~n", [Y]) end, lists:zipwith(fun(X,_)->X end, Lines, lists:seq(1, length(Lines)))).
lists:foreach(fun (Y) -> io:format("~s~n", [Y]) end, lists:zipwith(fun(X,_)->X end, Lines, lists:seq(1, length(Lines)))).
</syntaxhighlight>
</lang>


=={{header|ERRE}}==
=={{header|ERRE}}==
Line 1,357: Line 1,357:
=={{header|Euphoria}}==
=={{header|Euphoria}}==
Process text stream line-by-line:
Process text stream line-by-line:
<lang Euphoria>procedure process_line_by_line(integer fn)
<syntaxhighlight lang="euphoria">procedure process_line_by_line(integer fn)
object line
object line
while 1 do
while 1 do
Line 1,366: Line 1,366:
-- process the line
-- process the line
end while
end while
end procedure</lang>
end procedure</syntaxhighlight>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
Using a sequence expression:
Using a sequence expression:
<lang fsharp>
<syntaxhighlight lang="fsharp">
let lines_of_file file =
let lines_of_file file =
seq { use stream = System.IO.File.OpenRead file
seq { use stream = System.IO.File.OpenRead file
Line 1,376: Line 1,376:
while not reader.EndOfStream do
while not reader.EndOfStream do
yield reader.ReadLine() }
yield reader.ReadLine() }
</syntaxhighlight>
</lang>
The file is reopened every time the sequence is traversed and lines are read on-demand so this can handle arbitrarily-large files.
The file is reopened every time the sequence is traversed and lines are read on-demand so this can handle arbitrarily-large files.


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>"file.txt" utf8 [ [ process-line ] each-line ] with-file-reader</lang>
<syntaxhighlight lang="factor">"file.txt" utf8 [ [ process-line ] each-line ] with-file-reader</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Line 1,386: Line 1,386:
An input stream can be from a string or from a file. The method <code>eachLine</code> will divide the stream by linebreaks. The method <code>readStrToken</code> takes two arguments: a maximum size to read, and a function to decide when to stop reading - by default, it stops when it finds a white space.
An input stream can be from a string or from a file. The method <code>eachLine</code> will divide the stream by linebreaks. The method <code>readStrToken</code> takes two arguments: a maximum size to read, and a function to decide when to stop reading - by default, it stops when it finds a white space.


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 1,413: Line 1,413:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
{{works with|GNU Forth}}
{{works with|GNU Forth}}
<lang forth>4096 constant max-line
<syntaxhighlight lang="forth">4096 constant max-line
: read-lines
: read-lines
begin stdin pad max-line read-line throw
begin stdin pad max-line read-line throw
while pad swap \ addr len is the line of data, excluding newline
while pad swap \ addr len is the line of data, excluding newline
2drop
2drop
repeat ;</lang>
repeat ;</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 1,428: Line 1,428:
The code read line-by-line, but the maximum length of the line is limited (by a parameter)
The code read line-by-line, but the maximum length of the line is limited (by a parameter)


<lang fortran>program BasicInputLoop
<syntaxhighlight lang="fortran">program BasicInputLoop


implicit none
implicit none
Line 1,447: Line 1,447:
end if
end if


end program BasicInputLoop</lang>
end program BasicInputLoop</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Dim line_ As String ' line is a keyword
Dim line_ As String ' line is a keyword
Line 1,463: Line 1,463:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>while (line = readStdin[]) != undef
<syntaxhighlight lang="frink">while (line = readStdin[]) != undef
println[line]
println[line]
</syntaxhighlight>
</lang>


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
Note: This code goes beyond simply specifying the file to open. It includes a dialog window that allows the user to select a text file to read. The entire contents of the file are read in at once, rather than line by line.
Note: This code goes beyond simply specifying the file to open. It includes a dialog window that allows the user to select a text file to read. The entire contents of the file are read in at once, rather than line by line.
<lang futurebasic>include "NSLog.incl"
<syntaxhighlight lang="futurebasic">include "NSLog.incl"


local fn ReadTextFile
local fn ReadTextFile
Line 1,491: Line 1,491:
fn ReadTextFile
fn ReadTextFile


HandleEvents</lang>
HandleEvents</syntaxhighlight>


=={{header|gnuplot}}==
=={{header|gnuplot}}==
The following gnuplot script echoes standard input
The following gnuplot script echoes standard input
to standard output line-by-line until the end of the stream.
to standard output line-by-line until the end of the stream.
<lang gnuplot>!cat</lang>
<syntaxhighlight lang="gnuplot">!cat</syntaxhighlight>
It makes use of the ability of gnuplot to spawn shell commands.
It makes use of the ability of gnuplot to spawn shell commands.
In that sense it might be considered cheating.
In that sense it might be considered cheating.
Line 1,506: Line 1,506:
=={{header|Go}}==
=={{header|Go}}==
The following reads a line at a time from stdin.
The following reads a line at a time from stdin.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,531: Line 1,531:
_ = s
_ = s
}
}
}</lang>
}</syntaxhighlight>
Or, using <code>bufio.Scanner</code> you can read
Or, using <code>bufio.Scanner</code> you can read
line at a time,
line at a time,
Line 1,537: Line 1,537:
byte or Unicode code point at a time,
byte or Unicode code point at a time,
or by any custom "split function".
or by any custom "split function".
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,560: Line 1,560:
log.Fatal(err)
log.Fatal(err)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def lineMap = [:]
<syntaxhighlight lang="groovy">def lineMap = [:]
System.in.eachLine { line, i ->
System.in.eachLine { line, i ->
lineMap[i] = line
lineMap[i] = line
}
}
lineMap.each { println it }</lang>
lineMap.each { println it }</syntaxhighlight>


{{out|Test}}
{{out|Test}}
Line 1,594: Line 1,594:
The whole contents of a file can be read lazily. The standard functions ''lines'' and ''words'' convert that lazily into the lists of lines resp. words. Usually, one wouldn't use extra routines for that, but just use ''readFile'' and then put 'lines' or ''words'' somewhere in the next processing step.
The whole contents of a file can be read lazily. The standard functions ''lines'' and ''words'' convert that lazily into the lists of lines resp. words. Usually, one wouldn't use extra routines for that, but just use ''readFile'' and then put 'lines' or ''words'' somewhere in the next processing step.


<lang haskell>import System.IO
<syntaxhighlight lang="haskell">import System.IO


readLines :: Handle -> IO [String]
readLines :: Handle -> IO [String]
Line 1,604: Line 1,604:
readWords h = do
readWords h = do
s <- hGetContents h
s <- hGetContents h
return $ words s</lang>
return $ words s</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang HicEst>CHARACTER name='myfile.txt', string*1000
<syntaxhighlight lang="hicest">CHARACTER name='myfile.txt', string*1000


OPEN(FIle=name, OLD, LENgth=bytes, IOStat=errorcode, ERror=9)
OPEN(FIle=name, OLD, LENgth=bytes, IOStat=errorcode, ERror=9)
Line 1,616: Line 1,616:
ENDDO
ENDDO


9 WRITE(Messagebox, Name) line, errorcode</lang>
9 WRITE(Messagebox, Name) line, errorcode</syntaxhighlight>


=={{header|i}}==
=={{header|i}}==
<lang i>software {
<syntaxhighlight lang="i">software {
loop {
loop {
read()
read()
Line 1,626: Line 1,626:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>link str2toks
<syntaxhighlight lang="icon">link str2toks
# call either words or lines depending on what you want to do.
# call either words or lines depending on what you want to do.
procedure main()
procedure main()
Line 1,642: Line 1,642:
local line
local line
while line := read() do line ? every write(str2toks())
while line := read() do line ? every write(str2toks())
end</lang>
end</syntaxhighlight>
{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}
See [http://www.cs.arizona.edu/icon/library/src/procs/str2toks.icn str2toks]
See [http://www.cs.arizona.edu/icon/library/src/procs/str2toks.icn str2toks]
Line 1,648: Line 1,648:
=={{header|J}}==
=={{header|J}}==
Script "read-input-until-eof.ijs":
Script "read-input-until-eof.ijs":
<lang J>#!/Applications/j602/bin/jconsole
<syntaxhighlight lang="j">#!/Applications/j602/bin/jconsole
NB. read input until EOF
NB. read input until EOF
((1!:1) 3)(1!:2) 4
((1!:1) 3)(1!:2) 4
exit ''</lang>
exit ''</syntaxhighlight>
Example:
Example:
<lang J>$ ./read-input-to-eof.ijs <<EOF
<syntaxhighlight lang="j">$ ./read-input-to-eof.ijs <<EOF
> abc
> abc
> def
> def
Line 1,662: Line 1,662:
def
def
ghi
ghi
now is the time for all good men ...</lang>
now is the time for all good men ...</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Some people prefer <tt>Scanner</tt> or <tt>BufferedReader</tt>, so a way with each is presented.
Some people prefer <tt>Scanner</tt> or <tt>BufferedReader</tt>, so a way with each is presented.
<lang java>import java.io.InputStream;
<syntaxhighlight lang="java">import java.io.InputStream;
import java.util.Scanner;
import java.util.Scanner;


Line 1,690: Line 1,690:
}
}
}
}
}</lang>
}</syntaxhighlight>
Or
Or
<lang java>import java.io.BufferedReader;
<syntaxhighlight lang="java">import java.io.BufferedReader;
import java.io.IOException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InputStreamReader;
Line 1,722: Line 1,722:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 1,734: Line 1,734:


As above, this operates on standard input
As above, this operates on standard input
<lang javascript>var text_stream = WScript.StdIn;
<syntaxhighlight lang="javascript">var text_stream = WScript.StdIn;
var i = 0;
var i = 0;


Line 1,741: Line 1,741:
// do something with line
// do something with line
WScript.echo(++i + ": " + line);
WScript.echo(++i + ": " + line);
}</lang>
}</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Line 1,748: Line 1,748:
.
.


For example, to echo each line of text in a file, one could invoke jq as follows:<lang jq>jq -r -R . FILENAME
For example, to echo each line of text in a file, one could invoke jq as follows:<syntaxhighlight lang="jq">jq -r -R . FILENAME
</syntaxhighlight>
</lang>


If the input file consists of well-formed JSON entities (including scalars), then the following invocation could be used to "pretty-print" the input: <lang jq>jq . FILENAME</lang>
If the input file consists of well-formed JSON entities (including scalars), then the following invocation could be used to "pretty-print" the input: <syntaxhighlight lang="jq">jq . FILENAME</syntaxhighlight>


Other options, e.g. to emit JSON in compact form, also exist.
Other options, e.g. to emit JSON in compact form, also exist.


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>/* Input loop in Jsish */
<syntaxhighlight lang="javascript">/* Input loop in Jsish */


var line;
var line;
Line 1,763: Line 1,763:
while (line = console.input()) { cs += line.length; ls += 1; }
while (line = console.input()) { cs += line.length; ls += 1; }


printf("%d lines, %d characters\n", ls, cs);</lang>
printf("%d lines, %d characters\n", ls, cs);</syntaxhighlight>


{{out}}
{{out}}
Line 1,772: Line 1,772:
We create a text stream and read the lines from the stream one by one, printing them on screen.
We create a text stream and read the lines from the stream one by one, printing them on screen.
Note that the lines end by a newline, except the last one. The ending newlines are part of the strings returned by the function readline. Once the end of the stream is reached, readline returns an empty string.
Note that the lines end by a newline, except the last one. The ending newlines are part of the strings returned by the function readline. Once the end of the stream is reached, readline returns an empty string.
<lang julia>stream = IOBuffer("1\n2\n3\n4\n\n6")
<syntaxhighlight lang="julia">stream = IOBuffer("1\n2\n3\n4\n\n6")


while !eof(stream)
while !eof(stream)
line = readline(stream)
line = readline(stream)
println(line)
println(line)
end</lang>
end</syntaxhighlight>
{{Out}}
{{Out}}
<pre>1
<pre>1
Line 1,787: Line 1,787:


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


import java.util.*
import java.util.*
Line 1,803: Line 1,803:
words.add(input)
words.add(input)
}
}
}</lang>
}</syntaxhighlight>
Sample input/output:
Sample input/output:
{{out}}
{{out}}
Line 1,825: Line 1,825:


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>: read-lines do read . "\n" . eof if break then loop ;
<syntaxhighlight lang="lang5">: read-lines do read . "\n" . eof if break then loop ;
: ==>contents
: ==>contents
'< swap open 'fh set fh fin read-lines fh close ;
'< swap open 'fh set fh fin read-lines fh close ;


'file.txt ==>contents</lang>
'file.txt ==>contents</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">
<lang Lasso>
local(
local(
myfile = file('//path/to/file.txt'),
myfile = file('//path/to/file.txt'),
Line 1,842: Line 1,842:
}
}


#textresult -> join('<br />')</lang>
#textresult -> join('<br />')</syntaxhighlight>


Result:
Result:
Line 1,850: Line 1,850:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
filedialog "Open","*.txt",file$
filedialog "Open","*.txt",file$
if file$="" then end
if file$="" then end
Line 1,859: Line 1,859:
wend
wend
close #f
close #f
end </lang>
end </syntaxhighlight>


=={{header|LIL}}==
=={{header|LIL}}==
From the canread.lil sample that ships with LIL.
From the canread.lil sample that ships with LIL.


<lang tcl>#
<syntaxhighlight lang="tcl">#
# canread test (note that canread is not available in LIL/FPLIL itself
# canread test (note that canread is not available in LIL/FPLIL itself
# but provided by the command line interfaces in main.c/lil.pas)
# but provided by the command line interfaces in main.c/lil.pas)
Line 1,881: Line 1,881:
inc count
inc count
}
}
print $count lines</lang>
print $count lines</syntaxhighlight>


{{out}}
{{out}}
Line 1,892: Line 1,892:
* readword - returns a line as a single word, or an empty list if it reached the end of file
* 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
* readrawline - returns a line as a single word, with no characters escaped
<lang logo>while [not eof?] [print readline]</lang>
<syntaxhighlight lang="logo">while [not eof?] [print readline]</syntaxhighlight>


=={{header|LSL}}==
=={{header|LSL}}==
Line 1,898: Line 1,898:


To test it yourself; rez a box on the ground, add the following as a New Script, create a notecard named "Input_Loop_Data_Source.txt", and put what ever data you want in it (in this case I just put a copy of the source code.)
To test it yourself; rez a box on the ground, add the following as a New Script, create a notecard named "Input_Loop_Data_Source.txt", and put what ever data you want in it (in this case I just put a copy of the source code.)
<lang LSL>string sNOTECARD = "Input_Loop_Data_Source.txt";
<syntaxhighlight lang="lsl">string sNOTECARD = "Input_Loop_Data_Source.txt";
default {
default {
integer iNotecardLine = 0;
integer iNotecardLine = 0;
Line 1,913: Line 1,913:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Reading 'Input_Loop_Data_Source.txt'
<pre>Reading 'Input_Loop_Data_Source.txt'
Line 1,935: Line 1,935:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>lines = {}
<syntaxhighlight lang="lua">lines = {}
str = io.read()
str = io.read()
while str do
while str do
table.insert(lines,str)
table.insert(lines,str)
str = io.read()
str = io.read()
end</lang>
end</syntaxhighlight>


=== Via generic for loop ===
=== Via generic for loop ===
Reads line-by-line via an iterator (from stdin). Substitute <code>io.lines()</code> with <code>io.open(filename, "r"):lines()</code> to read from a file.
Reads line-by-line via an iterator (from stdin). Substitute <code>io.lines()</code> with <code>io.open(filename, "r"):lines()</code> to read from a file.


<lang lua>lines = {}
<syntaxhighlight lang="lua">lines = {}


for line in io.lines() do
for line in io.lines() do
table.insert(lines, line) -- add the line to the list of lines
table.insert(lines, line) -- add the line to the list of lines
end</lang>
end</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Document A$={1st Line
Document A$={1st Line
2nd line
2nd line
Line 1,976: Line 1,976:
\\ List of current variables (in any scope, public only)
\\ List of current variables (in any scope, public only)
List
List
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
readinput:=proc(filename)
readinput:=proc(filename)
local line,file;
local line,file;
Line 1,989: Line 1,989:
end do;
end do;
end proc;
end proc;
</syntaxhighlight>
</lang>


=={{header|MACRO-10}}==
=={{header|MACRO-10}}==
<syntaxhighlight lang="macro-10">
<lang MACRO-10>
TITLE Input Loop
TITLE Input Loop


Line 2,111: Line 2,111:


END GO
END GO
</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>stream = OpenRead["file.txt"];
<syntaxhighlight lang="mathematica">stream = OpenRead["file.txt"];
While[a != EndOfFile, Read[stream, Word]];
While[a != EndOfFile, Read[stream, Word]];
Close[stream]</lang>
Close[stream]</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
this function will read a file line by line.
this function will read a file line by line.
<lang MAXScript>fn ReadAFile FileName =
<syntaxhighlight lang="maxscript">fn ReadAFile FileName =
(
(
local in_file = openfile FileName
local in_file = openfile FileName
Line 2,129: Line 2,129:
)
)
close in_file
close in_file
)</lang>
)</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang>
<syntaxhighlight lang="text">
:- module input_loop.
:- module input_loop.
:- interface.
:- interface.
Line 2,164: Line 2,164:
io.set_exit_status(1, !IO)
io.set_exit_status(1, !IO)
).
).
</syntaxhighlight>
</lang>


=={{header|mIRC Scripting Language}}==
=={{header|mIRC Scripting Language}}==
<lang mirc>var %n = 1
<syntaxhighlight lang="mirc">var %n = 1
while (%n <= $lines(input.txt)) {
while (%n <= $lines(input.txt)) {
write output.txt $read(input.txt,%n)
write output.txt $read(input.txt,%n)
inc %n
inc %n
}</lang>
}</syntaxhighlight>


=={{header|ML/I}}==
=={{header|ML/I}}==
The very nature of ML/I is that its default behaviour
The very nature of ML/I is that its default behaviour
is to copy from input to output until it reaches end of file.
is to copy from input to output until it reaches end of file.
<lang ML/I></lang>
<syntaxhighlight lang="ml/i"></syntaxhighlight>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>PROCEDURE ReadName (VAR str : ARRAY OF CHAR);
<syntaxhighlight lang="modula2">PROCEDURE ReadName (VAR str : ARRAY OF CHAR);


VAR n : CARDINAL;
VAR n : CARDINAL;
Line 2,201: Line 2,201:
IF n <= HIGH (str) THEN str [n-1] := 0C END;
IF n <= HIGH (str) THEN str [n-1] := 0C END;
lastCh := ch
lastCh := ch
END ReadName;</lang>
END ReadName;</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE Output EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE Output EXPORTS Main;


IMPORT Rd, Wr, Stdio;
IMPORT Rd, Wr, Stdio;
Line 2,217: Line 2,217:
Wr.PutText(Stdio.stdout, buf);
Wr.PutText(Stdio.stdout, buf);
END;
END;
END Output.</lang>
END Output.</syntaxhighlight>


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


Line 2,242: Line 2,242:


return
return
</syntaxhighlight>
</lang>


=== Using Java <tt>Scanner</tt> ===
=== Using Java <tt>Scanner</tt> ===
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,265: Line 2,265:


return
return
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
Read from stdin until end of data has been reached:
Read from stdin until end of data has been reached:
<lang nim>var line = ""
<syntaxhighlight lang="nim">var line = ""
while stdin.readLine(line):
while stdin.readLine(line):
echo line</lang>
echo line</syntaxhighlight>
Choose splitting string:
Choose splitting string:
<lang nim>import strutils
<syntaxhighlight lang="nim">import strutils


var lines = stdin.readAll()
var lines = stdin.readAll()
for line in lines.split("\n"):
for line in lines.split("\n"):
echo line</lang>
echo line</syntaxhighlight>


Read from a known text file:
Read from a known text file:
<lang nim>var i = open("input.txt")
<syntaxhighlight lang="nim">var i = open("input.txt")
for line in i.lines:
for line in i.lines:
discard # process line
discard # process line
i.close()</lang>
i.close()</syntaxhighlight>


Another, shorter, way to do this:
Another, shorter, way to do this:
<lang nim>for line in "input.text".lines:
<syntaxhighlight lang="nim">for line in "input.text".lines:
discard # process line</lang>
discard # process line</syntaxhighlight>


=={{header|NodeJS}}==
=={{header|NodeJS}}==
<lang nodejs>
<syntaxhighlight lang="nodejs">
#!/usr/bin/env node
#!/usr/bin/env node


Line 2,315: Line 2,315:
const stdin = stdinLineByLine();
const stdin = stdinLineByLine();
stdin.on('line', console.log);
stdin.on('line', console.log);
</syntaxhighlight>
</lang>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Works with oo2c Version 2
Works with oo2c Version 2
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE InputLoop;
MODULE InputLoop;
IMPORT
IMPORT
Line 2,338: Line 2,338:
END
END
END InputLoop.
END InputLoop.
</syntaxhighlight>
</lang>
Execute: InputLoop &lt; Inputloop.Mod<br/>
Execute: InputLoop &lt; Inputloop.Mod<br/>
Output:
Output:
Line 2,363: Line 2,363:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
use IO;
use IO;


Line 2,381: Line 2,381:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let rec read_lines ic =
<syntaxhighlight lang="ocaml">let rec read_lines ic =
try
try
let line = input_line ic in
let line = input_line ic in
line :: read_lines ic
line :: read_lines ic
with End_of_file ->
with End_of_file ->
[]</lang>
[]</syntaxhighlight>


The version above will work for small files, but it is not tail-recursive. <br />
The version above will work for small files, but it is not tail-recursive. <br />
Below will be more scalable:
Below will be more scalable:


<lang ocaml>let read_line_opt ic =
<syntaxhighlight lang="ocaml">let read_line_opt ic =
try Some (input_line ic)
try Some (input_line ic)
with End_of_file -> None
with End_of_file -> None
Line 2,405: Line 2,405:
in
in
loop []
loop []
;;</lang>
;;</syntaxhighlight>


Or with a higher order function:
Or with a higher order function:


<lang ocaml>let read_lines f ic =
<syntaxhighlight lang="ocaml">let read_lines f ic =
let rec loop () =
let rec loop () =
try f (input_line ic); loop ()
try f (input_line ic); loop ()
Line 2,418: Line 2,418:
let () =
let () =
let ic = open_in Sys.argv.(1) in
let ic = open_in Sys.argv.(1) in
read_lines print_endline ic</lang>
read_lines print_endline ic</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 2,424: Line 2,424:
Reads a file line by line and write each line on standard output :
Reads a file line by line and write each line on standard output :


<lang Oforth>: readFile(filename) File new(filename) apply(#println) ; </lang>
<syntaxhighlight lang="oforth">: readFile(filename) File new(filename) apply(#println) ; </syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>%% Returns a list of lines.
<syntaxhighlight lang="oz">%% Returns a list of lines.
%% Text: an instance of Open.text (a mixin class)
%% Text: an instance of Open.text (a mixin class)
fun {ReadAll Text}
fun {ReadAll Text}
Line 2,433: Line 2,433:
[] Line then Line|{ReadAll Text}
[] Line then Line|{ReadAll Text}
end
end
end</lang>
end</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>{ for stdio }
<syntaxhighlight lang="pascal">{ for stdio }


var
var
Line 2,468: Line 2,468:
closefile(f);
closefile(f);


end;</lang>
end;</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
The angle brackets operator ( <tt><...></tt> ) reads one line at a time from a filehandle in scalar context:
The angle brackets operator ( <tt><...></tt> ) reads one line at a time from a filehandle in scalar context:
<lang perl>open FH, "< $filename" or die "can't open file: $!";
<syntaxhighlight lang="perl">open FH, "< $filename" or die "can't open file: $!";
while (my $line = <FH>) {
while (my $line = <FH>) {
chomp $line; # removes trailing newline
chomp $line; # removes trailing newline
# process $line
# process $line
}
}
close FH or die "can't close file: $!";</lang>
close FH or die "can't close file: $!";</syntaxhighlight>


Or you can get a list of all lines when you use it in list context:
Or you can get a list of all lines when you use it in list context:
<lang perl>@lines = <FH>;</lang>
<syntaxhighlight lang="perl">@lines = <FH>;</syntaxhighlight>


Or a simpler program for lines of files entered as command line arguments or standard input:
Or a simpler program for lines of files entered as command line arguments or standard input:
<lang perl>while (<>) {
<syntaxhighlight lang="perl">while (<>) {
# $_ contains a line
# $_ contains a line
}</lang>
}</syntaxhighlight>


Invoking perl with the -p or -n option implies the above loop, executing its code once per input line, with the line stored in $_. -p will print $_ automatically at the end of each iteration, -n will not.
Invoking perl with the -p or -n option implies the above loop, executing its code once per input line, with the line stored in $_. -p will print $_ automatically at the end of each iteration, -n will not.
Line 2,505: Line 2,505:
{{trans|Euphoria}}
{{trans|Euphoria}}
Process text stream line-by-line:
Process text stream line-by-line:
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">process_line_by_line</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">process_line_by_line</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
Line 2,517: Line 2,517:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>$fh = fopen($filename, 'r');
<syntaxhighlight lang="php">$fh = fopen($filename, 'r');
if ($fh) {
if ($fh) {
while (!feof($fh)) {
while (!feof($fh)) {
Line 2,527: Line 2,527:
}
}
fclose($fh);
fclose($fh);
}</lang>
}</syntaxhighlight>


Or you can get an array of all the lines in the file:
Or you can get an array of all the lines in the file:
<lang php>$lines = file($filename);</lang>
<syntaxhighlight lang="php">$lines = file($filename);</syntaxhighlight>


Or you can get the entire file as a string:
Or you can get the entire file as a string:
<lang php>$contents = file_get_contents($filename);</lang>
<syntaxhighlight lang="php">$contents = file_get_contents($filename);</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>main =>
<syntaxhighlight lang="picat">main =>
Reader = open("file.txt"),
Reader = open("file.txt"),
while(not at_end_of_stream(Reader))
while(not at_end_of_stream(Reader))
Line 2,542: Line 2,542:
println(L)
println(L)
end,
end,
close(Reader).</lang>
close(Reader).</syntaxhighlight>




=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
This reads all lines in a file, and returns them as a list of lists
This reads all lines in a file, and returns them as a list of lists
<lang PicoLisp>(in "file.txt"
<syntaxhighlight lang="picolisp">(in "file.txt"
(make
(make
(until (eof)
(until (eof)
(link (line)) ) ) )</lang>
(link (line)) ) ) )</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>declare line character (200) varying;
<syntaxhighlight lang="pli">declare line character (200) varying;


open file (in) title ('/TEXT.DAT,type(text),recsize(200)' );
open file (in) title ('/TEXT.DAT,type(text),recsize(200)' );
Line 2,561: Line 2,561:
get file(in) edit (line) (L);
get file(in) edit (line) (L);
put skip list (line);
put skip list (line);
end;</lang>
end;</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang Powershell>Get-Content c:\file.txt |
<syntaxhighlight lang="powershell">Get-Content c:\file.txt |
ForEach-Object {
ForEach-Object {
$_
$_
}</lang>
}</syntaxhighlight>
or
or
<lang Powershell>ForEach-Object -inputobject (get-content c:\file.txt) {$_}</lang>
<syntaxhighlight lang="powershell">ForEach-Object -inputobject (get-content c:\file.txt) {$_}</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
File objects can be read bytewise, characterwise (ASCII or UNICODE), floatwise, doublewise, integerwise, linewise ...
File objects can be read bytewise, characterwise (ASCII or UNICODE), floatwise, doublewise, integerwise, linewise ...
<lang PureBasic>If OpenConsole()
<syntaxhighlight lang="purebasic">If OpenConsole()
; file based line wise
; file based line wise
If ReadFile(0, "Text.txt")
If ReadFile(0, "Text.txt")
Line 2,589: Line 2,589:
CloseFile(1)
CloseFile(1)
EndIf
EndIf
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Line 2,595: Line 2,595:
To create a Python3 input loop use python's `input()` function.
To create a Python3 input loop use python's `input()` function.


<lang python>while(True):
<syntaxhighlight lang="python">while(True):
x = input("What is your age? ")
x = input("What is your age? ")
print(x)</lang>
print(x)</syntaxhighlight>


Python file objects can be iterated like lists:
Python file objects can be iterated like lists:


<lang python>my_file = open(filename, 'r')
<syntaxhighlight lang="python">my_file = open(filename, 'r')
try:
try:
for line in my_file:
for line in my_file:
pass # process line, includes newline
pass # process line, includes newline
finally:
finally:
my_file.close()</lang>
my_file.close()</syntaxhighlight>


One can open a new stream for read and have it automatically close when done, with a new "with" statement:
One can open a new stream for read and have it automatically close when done, with a new "with" statement:
<lang python>#from __future__ import with_statement # is not needed in Python 3.6
<syntaxhighlight lang="python">#from __future__ import with_statement # is not needed in Python 3.6


with open(filename, 'r') as f:
with open(filename, 'r') as f:
for line in f:
for line in f:
pass # process line, includes newline</lang>
pass # process line, includes newline</syntaxhighlight>


You can also get lines manually from a file:
You can also get lines manually from a file:
<lang python>line = my_file.readline() # returns a line from the file
<syntaxhighlight lang="python">line = my_file.readline() # returns a line from the file
lines = my_file.readlines() # returns a list of the rest of the lines from the file</lang>
lines = my_file.readlines() # returns a list of the rest of the lines from the file</syntaxhighlight>
This does not mix well with the iteration, however.
This does not mix well with the iteration, however.




When you want to read from stdin, or (multiple) filenames are given on the command line:
When you want to read from stdin, or (multiple) filenames are given on the command line:
<lang python>import fileinput
<syntaxhighlight lang="python">import fileinput
for line in fileinput.input():
for line in fileinput.input():
pass # process line, includes newline</lang>
pass # process line, includes newline</syntaxhighlight>
The fileinput module can also do inplace file editing, follow line counts, and the name of the current file being read etc.
The fileinput module can also do inplace file editing, follow line counts, and the name of the current file being read etc.


=={{header|R}}==
=={{header|R}}==
Note that read.csv and read.table provide alternatives for files with 'dataset' style contents.
Note that read.csv and read.table provide alternatives for files with 'dataset' style contents.
<lang rsplus>lines <- readLines("file.txt")</lang>
<syntaxhighlight lang="rsplus">lines <- readLines("file.txt")</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


The following prints input lines from standard input to standard output:
The following prints input lines from standard input to standard output:
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(copy-port (current-input-port) (current-output-port))
(copy-port (current-input-port) (current-output-port))
</syntaxhighlight>
</lang>


=={{header|Rapira}}==
=={{header|Rapira}}==
<lang Rapira>while 1 do
<syntaxhighlight lang="rapira">while 1 do
input text: str
input text: str
output: str
output: str
od</lang>
od</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,652: Line 2,652:
'''Line-by-line''' <small>''(line endings are automatically stripped)''</small>
'''Line-by-line''' <small>''(line endings are automatically stripped)''</small>


*From a file:<lang perl6>for "filename.txt".IO.lines -> $line {
*From a file:<syntaxhighlight lang="raku" line>for "filename.txt".IO.lines -> $line {
...
...
}</lang>
}</syntaxhighlight>
*From standard input:<lang perl6>for $*IN.lines -> $line {
*From standard input:<syntaxhighlight lang="raku" line>for $*IN.lines -> $line {
...
...
}</lang>
}</syntaxhighlight>
*From a pipe:<lang perl6>for run(«find -iname *.txt», :out).out.lines -> $filename {
*From a pipe:<syntaxhighlight lang="raku" line>for run(«find -iname *.txt», :out).out.lines -> $filename {
...
...
}</lang>
}</syntaxhighlight>
*From a pipe, with custom line separator <small>''(in this example to handle filenames containing newlines)''</small>:<lang perl6>for run(«find -iname *.txt -print0», :nl«\0», :out).out.lines -> $filename {
*From a pipe, with custom line separator <small>''(in this example to handle filenames containing newlines)''</small>:<syntaxhighlight lang="raku" line>for run(«find -iname *.txt -print0», :nl«\0», :out).out.lines -> $filename {
...
...
}</lang>
}</syntaxhighlight>


'''Word-by-word'''
'''Word-by-word'''
*From a file <lang perl6>for "filename.txt".IO.words -> $word {
*From a file <syntaxhighlight lang="raku" line>for "filename.txt".IO.words -> $word {
...
...
}</lang>
}</syntaxhighlight>
*From standard input or a pipe, accordingly.
*From standard input or a pipe, accordingly.


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Basic Input Loop"
Title: "Basic Input Loop"
URL: http://rosettacode.org/wiki/Basic_input_loop
URL: http://rosettacode.org/wiki/Basic_input_loop
Line 2,692: Line 2,692:
f: next f ; Advance to next line.
f: next f ; Advance to next line.
]
]
close f</lang>
close f</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 2,698: Line 2,698:
{{works with|oorexx and Regina}}
{{works with|oorexx and Regina}}
Reading line by line from the standard input using <tt>linein</tt> and <tt>lines</tt> did not work.
Reading line by line from the standard input using <tt>linein</tt> and <tt>lines</tt> did not work.
<lang rexx>do while stream(stdin, "State") <> "NOTREADY"
<syntaxhighlight lang="rexx">do while stream(stdin, "State") <> "NOTREADY"
call charout ,charin(stdin)
call charout ,charin(stdin)
end</lang>
end</syntaxhighlight>


===version 1b===
===version 1b===
{{works with|oorexx and Regina}}
{{works with|oorexx and Regina}}
Apparently only lines() does not work
Apparently only lines() does not work
<lang rexx>Do Until input=''
<syntaxhighlight lang="rexx">Do Until input=''
input=linein(stdin)
input=linein(stdin)
Call lineout ,input
Call lineout ,input
End</lang>
End</syntaxhighlight>


===version 2===
===version 2===
{{works with|ARexx}}
{{works with|ARexx}}
<lang rexx>/* -- AREXX -- */
<syntaxhighlight lang="rexx">/* -- AREXX -- */
do until eof(stdin)
do until eof(stdin)
l = readln(stdin)
l = readln(stdin)
say l
say l
end</lang>
end</syntaxhighlight>


===version 3===
===version 3===
Line 2,722: Line 2,722:


Therefore, the following two REXX programs use the presence of a null line to indicate e-o-f.
Therefore, the following two REXX programs use the presence of a null line to indicate e-o-f.
<lang rexx>/*REXX program reads from the (console) default input stream until null*/
<syntaxhighlight lang="rexx">/*REXX program reads from the (console) default input stream until null*/
do until _==''
do until _==''
parse pull _
parse pull _
end /*until*/ /*stick a fork in it, we're done.*/</lang>
end /*until*/ /*stick a fork in it, we're done.*/</syntaxhighlight>


===version 4===
===version 4===
<lang rexx>/*REXX program reads from the (console) default input stream until null*/
<syntaxhighlight lang="rexx">/*REXX program reads from the (console) default input stream until null*/
do until _==''
do until _==''
_= linein()
_= linein()
end /*until*/ /*stick a fork in it, we're done.*/</lang>
end /*until*/ /*stick a fork in it, we're done.*/</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
fp = fopen("C:\Ring\ReadMe.txt","r")
fp = fopen("C:\Ring\ReadMe.txt","r")


Line 2,745: Line 2,745:
fclose(fp)
fclose(fp)


</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
Ruby input streams are IO objects. One can use IO#each or IO#each_line to iterate lines from a stream.
Ruby input streams are IO objects. One can use IO#each or IO#each_line to iterate lines from a stream.


<lang ruby>stream = $stdin
<syntaxhighlight lang="ruby">stream = $stdin
stream.each do |line|
stream.each do |line|
# process line
# process line
end</lang>
end</syntaxhighlight>


IO objects are also Enumerable (like Array or Range), and have methods like Enumerable#map, which call IO#each to loop through lines from a stream.
IO objects are also Enumerable (like Array or Range), and have methods like Enumerable#map, which call IO#each to loop through lines from a stream.


<lang ruby># Create an array of lengths of every line.
<syntaxhighlight lang="ruby"># Create an array of lengths of every line.
ary = stream.map {|line| line.chomp.length}</lang>
ary = stream.map {|line| line.chomp.length}</syntaxhighlight>


''To open a new stream for reading, see [[Read a file line by line#Ruby]].''
''To open a new stream for reading, see [[Read a file line by line#Ruby]].''


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>open "\testFile.txt" for input as #f
<syntaxhighlight lang="runbasic">open "\testFile.txt" for input as #f
while not(eof(#f))
while not(eof(#f))
line input #f, a$
line input #f, a$
print a$
print a$
wend
wend
close #f</lang>
close #f</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust> use std::io::{self, BufReader, Read, BufRead};
<syntaxhighlight lang="rust"> use std::io::{self, BufReader, Read, BufRead};
use std::fs::File;
use std::fs::File;


Line 2,789: Line 2,789:
}
}
Ok(())
Ok(())
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
{{works with|Scala|2.10.3}}
{{works with|Scala|2.10.3}}
<lang scala> scala.io.Source.fromFile("input.txt").getLines().foreach {
<syntaxhighlight lang="scala"> scala.io.Source.fromFile("input.txt").getLines().foreach {
line => ... }</lang>
line => ... }</syntaxhighlight>


=={{header|sed}}==
=={{header|sed}}==
Line 2,818: Line 2,818:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const proc: main is func
const proc: main is func
Line 2,828: Line 2,828:
writeln("LINE: " <& line);
writeln("LINE: " <& line);
end while;
end while;
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
To read from the standard input, you can use '''STDIN''' as your '''fh'''.
To read from the standard input, you can use '''STDIN''' as your '''fh'''.
<lang ruby>var file = File(__FILE__)
<syntaxhighlight lang="ruby">var file = File(__FILE__)
file.open_r(\var fh, \var err) || die "#{file}: #{err}"
file.open_r(\var fh, \var err) || die "#{file}: #{err}"


Line 2,839: Line 2,839:
say word
say word
}
}
}</lang>
}</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>(File newNamed: 'README') reader sessionDo: [| :input | input lines do: [| :line | inform: line]].</lang>
<syntaxhighlight lang="slate">(File newNamed: 'README') reader sessionDo: [| :input | input lines do: [| :line | inform: line]].</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>|f|
<syntaxhighlight lang="smalltalk">|f|
f := FileStream open: 'afile.txt' mode: FileStream read.
f := FileStream open: 'afile.txt' mode: FileStream read.
[ f atEnd ] whileFalse: [ (f nextLine) displayNl ] .</lang>
[ f atEnd ] whileFalse: [ (f nextLine) displayNl ] .</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<lang snobol>loop output = input :s(loop)
<syntaxhighlight lang="snobol">loop output = input :s(loop)
end</lang>
end</syntaxhighlight>


=={{header|Sparkling}}==
=={{header|Sparkling}}==
<lang sparkling>var line;
<syntaxhighlight lang="sparkling">var line;
while (line = getline()) != nil {
while (line = getline()) != nil {
print(line);
print(line);
}</lang>
}</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>fun foldLines f init strm =
<syntaxhighlight lang="sml">fun foldLines f init strm =
case TextIO.inputLine strm of
case TextIO.inputLine strm of
SOME line => foldLines f (f (line, init)) strm
SOME line => foldLines f (f (line, init)) strm
| NONE => init</lang>
| NONE => init</syntaxhighlight>
Example: Output the lines from stdin in reverse order.
Example: Output the lines from stdin in reverse order.
<lang sml>val () = (print o foldLines op^ "") TextIO.stdIn</lang>
<syntaxhighlight lang="sml">val () = (print o foldLines op^ "") TextIO.stdIn</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>set fh [open $filename]
<syntaxhighlight lang="tcl">set fh [open $filename]
while {[gets $fh line] != -1} {
while {[gets $fh line] != -1} {
# process $line
# process $line
}
}
close $fh</lang>
close $fh</syntaxhighlight>
For “small” files, it is often more common to do this:
For “small” files, it is often more common to do this:
<lang tcl>set fh [open $filename]
<syntaxhighlight lang="tcl">set fh [open $filename]
set data [read $fh]
set data [read $fh]
close $fh
close $fh
foreach line [split $data \n] {
foreach line [split $data \n] {
# process line
# process line
}</lang>
}</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
file="a.txt"
file="a.txt"
Line 2,892: Line 2,892:
ENDLOOP
ENDLOOP
ENDACCESS source
ENDACCESS source
</syntaxhighlight>
</lang>


=={{header|TypeScript}}==
=={{header|TypeScript}}==
<lang typescript>
<syntaxhighlight lang="typescript">
#!/usr/bin/env node
#!/usr/bin/env node


Line 2,922: Line 2,922:
stdin.on('line', console.log);
stdin.on('line', console.log);


</syntaxhighlight>
</lang>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
When there is something to do with the input, here is a loop:
When there is something to do with the input, here is a loop:
<lang bash>while read line ; do
<syntaxhighlight lang="bash">while read line ; do
# examine or do something to the text in the "line" variable
# examine or do something to the text in the "line" variable
echo "$line"
echo "$line"
done</lang>
done</syntaxhighlight>
The following echoes standard input to standard output line-by-line until the end of the stream.
The following echoes standard input to standard output line-by-line until the end of the stream.
<lang bash>cat < /dev/stdin > /dev/stdout</lang>
<syntaxhighlight lang="bash">cat < /dev/stdin > /dev/stdout</syntaxhighlight>
Since <code>cat</code> defaults to reading from standard input and writing to standard output, this can be further simplified to the following.
Since <code>cat</code> defaults to reading from standard input and writing to standard output, this can be further simplified to the following.
<lang bash>cat</lang>
<syntaxhighlight lang="bash">cat</syntaxhighlight>


=={{header|UnixPipes}}==
=={{header|UnixPipes}}==
Line 2,939: Line 2,939:


read by lines:
read by lines:
<lang bash>yes 'A B C D ' | while read x ; do echo -$x- ; done</lang>
<syntaxhighlight lang="bash">yes 'A B C D ' | while read x ; do echo -$x- ; done</syntaxhighlight>
read by words:
read by words:
<lang bash>yes 'A B C D ' | while read -d\ a ; do echo -$a- ; done</lang>
<syntaxhighlight lang="bash">yes 'A B C D ' | while read -d\ a ; do echo -$a- ; done</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>decl file f
<syntaxhighlight lang="ursa">decl file f
f.open "filename.txt"
f.open "filename.txt"
while (f.hasnext)
while (f.hasnext)
out (in string f) endl console
out (in string f) endl console
end while</lang>
end while</syntaxhighlight>


=={{header|Vala}}==
=={{header|Vala}}==
<lang vala>int main() {
<syntaxhighlight lang="vala">int main() {
string? s;
string? s;
while((s = stdin.read_line()) != null) {
while((s = stdin.read_line()) != null) {
Line 2,957: Line 2,957:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Public Sub test()
<syntaxhighlight lang="vb">Public Sub test()
Dim filesystem As Object, stream As Object, line As String
Dim filesystem As Object, stream As Object, line As String
Set filesystem = CreateObject("Scripting.FileSystemObject")
Set filesystem = CreateObject("Scripting.FileSystemObject")
Line 2,969: Line 2,969:
Loop
Loop
stream.Close
stream.Close
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
filepath = "SPECIFY PATH TO TEXT FILE HERE"
filepath = "SPECIFY PATH TO TEXT FILE HERE"


Line 2,985: Line 2,985:
objInFile.Close
objInFile.Close
Set objFSO = Nothing
Set objFSO = Nothing
</syntaxhighlight>
</lang>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
Line 2,991: Line 2,991:
This reads a stream line by line, outputing each line to the screen.
This reads a stream line by line, outputing each line to the screen.


<lang vbnet>Sub Consume(ByVal stream As IO.StreamReader)
<syntaxhighlight lang="vbnet">Sub Consume(ByVal stream As IO.StreamReader)
Dim line = stream.ReadLine
Dim line = stream.ReadLine
Do Until line Is Nothing
Do Until line Is Nothing
Line 2,997: Line 2,997:
line = stream.ReadLine
line = stream.ReadLine
Loop
Loop
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "io" for File
<syntaxhighlight lang="ecmascript">import "io" for File


File.open("input.txt") { |file|
File.open("input.txt") { |file|
Line 3,019: Line 3,019:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|x86 Assembly}}==
=={{header|x86 Assembly}}==


'''GAS, 64 bit (Linux)''': Compiled with <code>gcc -nostdlib</code>. Memory maps the file and outputs one line at a time. Try <code>./a.out file</code>, <code>./a.out < file</code>, or <code>./a.out <<< "Heredoc"</code>. It's a little like cat, but less functional.
'''GAS, 64 bit (Linux)''': Compiled with <code>gcc -nostdlib</code>. Memory maps the file and outputs one line at a time. Try <code>./a.out file</code>, <code>./a.out < file</code>, or <code>./a.out <<< "Heredoc"</code>. It's a little like cat, but less functional.
<lang x86>#define SYS_WRITE $1
<syntaxhighlight lang="x86">#define SYS_WRITE $1
#define SYS_OPEN $2
#define SYS_OPEN $2
#define SYS_CLOSE $3
#define SYS_CLOSE $3
Line 3,172: Line 3,172:
filesize: // 8 bytes.
filesize: // 8 bytes.
.quad 0
.quad 0
.zero STATSIZE-FSIZEOFF+8</lang>
.zero STATSIZE-FSIZEOFF+8</syntaxhighlight>


=={{header|XPL0}}==
=={{header|XPL0}}==
Text stream is a file redirected on command line i.e: <file.txt
Text stream is a file redirected on command line i.e: <file.txt
<lang XPL0>int C;
<syntaxhighlight lang="xpl0">int C;
[repeat \read file
[repeat \read file
repeat \read line
repeat \read line
Line 3,184: Line 3,184:
until C < $20; \CR, LF, or EOF
until C < $20; \CR, LF, or EOF
until C = \EOF\ $1A;
until C = \EOF\ $1A;
]</lang>
]</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
Line 3,191: Line 3,191:
Word by word isn't explicitly supported.
Word by word isn't explicitly supported.
If an object is stream-able, it supports methods like foreach, pump, apply, reduce, etc.
If an object is stream-able, it supports methods like foreach, pump, apply, reduce, etc.
<lang zkl>foreach line in (File("foo.txt")){...}
<syntaxhighlight lang="zkl">foreach line in (File("foo.txt")){...}
List(1,2,3).readln() // here, a "line" is a list element
List(1,2,3).readln() // here, a "line" is a list element
Utils.Helpers.zipWith(False, // enumerate a file
Utils.Helpers.zipWith(False, // enumerate a file
fcn(n,line){"%3d: %s".fmt(n,line).print()},[1..],File("cmp.zkl"))</lang>
fcn(n,line){"%3d: %s".fmt(n,line).print()},[1..],File("cmp.zkl"))</syntaxhighlight>