Anonymous user
Input loop: Difference between revisions
m
→{{header|Elena}}
m (Fixed typo in comment of MACRO-10 example.) |
imported>Arakov |
||
(19 intermediate revisions by 14 users not shown) | |||
Line 15:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program inputLoop64.s */
Line 176:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|Action!}}==
<
CHAR ARRAY line(255)
Line 197:
ReadStream(streamId)
Close(streamId)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Input_loop.png Screenshot from Atari 8-bit computer]
Line 227:
This example reads in a text stream from standard input line by line
and writes the output to standard output.
<
procedure Read_Stream is
Line 244:
end if;
end loop;
end Read_Stream;</
=={{header|Aime}}==
<
read_stream(file f)
{
Line 255:
# the read line available as -s-
}
}</
=={{header|ALGOL 68}}==
For file consisting of just one page - a typical linux/unix file:
<
PROC raise logical file end = (REF FILE f) BOOL: ( except logical file end );
on logical file end(stand in, raise logical file end);
Line 269:
except logical file end:
SKIP
)</
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.
<
PROC raise logical file end = (REF FILE f) BOOL: ( except logical file end );
on logical file end(stand in, raise logical file end);
Line 288:
except logical file end:
SKIP
)</
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}}==
<
string(80) line;
% allow the program to continue after reaching end-of-file %
Line 303:
read( line )
end
end.</
=={{header|AmigaE}}==
<
PROC consume_input(fh)
Line 331:
Close(fh)
ENDIF
ENDPROC</
=={{header|APL}}==
{{works with|GNU APL}}
<syntaxhighlight lang="apl">
h ← ⊃ (⎕fio['read_text'] 'corpus/sample1.txt')
⍴h
Line 350:
│ │
└─────────────────────────────────────────────────┘
</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 502:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
{{Output}}
<pre>
Line 519:
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">while [true][
i: input "> "
print i
]</syntaxhighlight>
=={{header|AutoHotkey}}==
This example reads the text of a source file line by line
and writes the output to a destination file.
<
{
FileAppend, %A_LoopReadLine%`n
}</
=={{header|AWK}}==
This just reads lines from stdin and prints them until EOF is read.
<syntaxhighlight lang
or, more idiomatic:
<syntaxhighlight lang
=={{header|BASIC}}==
==={{header|BASIC256}}===
<
open f, "test.txt"
Line 547 ⟶ 554:
end while
close f
end</
==={{header|OxygenBasic}}===
<syntaxhighlight lang="text">
uses Console
uses ParseUtil
Line 560 ⟶ 567:
wend
pause
</syntaxhighlight>
==={{header|QBasic}}===
{{works with|QBasic}}
{{works with|QuickBasic}}
<
WHILE NOT EOF(1)
Line 573 ⟶ 580:
CLOSE #1
END</
==={{header|True BASIC}}===
<
DO
Line 584 ⟶ 591:
CLOSE #1
END</
==={{header|Yabasic}}===
<
f = open(filename$)
Line 597 ⟶ 604:
close f
end</
==={{header|Applesoft BASIC}}===
<
110 D$ = CHR$(4)
120 PRINT D$"VERIFY"F$
Line 613 ⟶ 620:
190 POKE 216,0
200 IF PEEK(222) <> 5 THEN RESUME
210 PRINT D$"CLOSE"F$</
==={{header|BaCon}}===
<
'--- 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"
Line 631 ⟶ 638:
INCR i
WEND
</
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
This specifically relates to console input (stdin).
<
STD_OUTPUT_HANDLE = -11
SYS "GetStdHandle", STD_INPUT_HANDLE TO @hfile%(1)
Line 646 ⟶ 653:
INPUT A$
PRINT A$
UNTIL FALSE</
==={{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
<syntaxhighlight lang="commodorebasicv2">
10 rem input loop - rosetta code
11 rem open command channel, clear screen, switch to lower case
Line 677 ⟶ 684:
1110 print:print er;"- ";er$;" track:";tk;"sector:";sc
1120 return
</syntaxhighlight>
==={{header|IS-BASIC}}===
<
110 TEXT 80
120 INPUT PROMPT "File name: ":F$
Line 694 ⟶ 701:
220 PRINT EXSTRING$(EXTYPE)
230 END
240 END HANDLER</
Alternate solution:
<
110 INPUT PROMPT "File name: ":F$
120 WHEN EXCEPTION USE IOERROR
Line 707 ⟶ 714:
180 PRINT EXSTRING$(EXTYPE)
190 CLOSE #1
200 END HANDLER</
==={{header|uBasic/4tH}}===
<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>
This version tokenizes the line read and prints all individual words.
<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
p = Here() ' save cursor position
s = Tok(Ord(" ")) ' tokenize next word
Until p = Here() ' quit if cursor didn't progress
If Len(s) Then Print Show(s) ' print only full words
Loop ' next word
Loop ' next line
Close a
</syntaxhighlight>
=={{header|Batch File}}==
<
for /f %%i in (file.txt) do if %%i@ neq @ echo %%i
</syntaxhighlight>
=={{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.
<
a three line
text","test.txt",NEW)
Line 742 ⟶ 772:
)
& (fil$(,SET,-1)|out$"file closed")
);</
{{out}}
<pre>breakchar:SP, word 1:This
Line 755 ⟶ 785:
Reads arbitrarily long line each time and return a null-terminated string.
Caller is responsible for freeing the string.
<
#include <stdio.h>
Line 786 ⟶ 816:
}
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.IO;
Line 807 ⟶ 837:
}
}
}</
=={{header|C++}}==
The following functions send the words resp. lines
to a generic output iterator.
<
#include <istream>
#include <string>
Line 857 ⟶ 887:
}
</syntaxhighlight>
An alternate way to read words or lines is to use istream iterators:
<
template<class OutIt>
void read_words(std::istream& is, OutIt dest)
Line 888 ⟶ 918:
dest);
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(line-seq (java.io.BufferedReader. (java.io.FileReader. fname))))</
=={{header|COBOL}}==
{{works with|GNU Cobol|2.0}}
{{works with|Visual COBOL}}
<
PROGRAM-ID. input-loop.
Line 929 ⟶ 959:
CLOSE in-stream
.
END PROGRAM input-loop.</
=={{header|Common Lisp}}==
<
(with-open-file (stream (make-pathname :name filename) :direction :input)
(loop for line = (read-line stream nil nil)
while line
do (format t "~a~%" line))))</
=={{header|D}}==
<
import std.stdio;
Line 961 ⟶ 991:
line.writeln;
}
}</
{{libheader|Tango}}
<
import tango.text.stream.LineIterator;
Line 971 ⟶ 1,001:
// do something with each line
}
}</
{{libheader|Tango}}
<
import tango.text.stream.SimpleIterator;
Line 980 ⟶ 1,010:
// do something with each word
}
}</
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}}==
<
{$APPTYPE CONSOLE}
Line 1,001 ⟶ 1,031:
lReader.Free;
end;
end.</
=={{header|Déjà Vu}}==
<
!print( "Read a line: " !decode!utf-8 swap )
drop
!print "End of file."</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">repeat
l$ = input
until error = 1
print l$
.</
=={{header|Eiffel}}==
{{works with|Eiffel Studio|6.6}}
<syntaxhighlight lang="eiffel">
note
description : "{
Line 1,257 ⟶ 1,287:
end
</syntaxhighlight>
=={{header|Elena}}==
ELENA
Using ReaderEnumerator
<
import system'io;
import extensions'routines;
Line 1,269 ⟶ 1,299:
public program()
{
ReaderEnumerator.new(File.assign
}</
Using loop statement
<
public program()
{
using(var reader := File.assign
{
while (reader.Available)
Line 1,283 ⟶ 1,313:
}
}
}</
=={{header|Elixir}}==
<
def input_loop(stream) do
case IO.read(stream, :line) do
Line 1,297 ⟶ 1,327:
path = hd(System.argv)
File.open!(path, [:read], fn stream -> RC.input_loop(stream) end)</
=={{header|Erlang}}==
<
-module(read_files).
-export([main/0]).
Line 1,308 ⟶ 1,338:
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)))).
</syntaxhighlight>
=={{header|ERRE}}==
Line 1,334 ⟶ 1,364:
=={{header|Euphoria}}==
Process text stream line-by-line:
<
object line
while 1 do
Line 1,343 ⟶ 1,373:
-- process the line
end while
end procedure</
=={{header|F Sharp|F#}}==
Using a sequence expression:
<
let lines_of_file file =
seq { use stream = System.IO.File.OpenRead file
Line 1,353 ⟶ 1,383:
while not reader.EndOfStream do
yield reader.ReadLine() }
</syntaxhighlight>
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|Fantom}}==
Line 1,363 ⟶ 1,393:
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.
<
class Main
{
Line 1,390 ⟶ 1,420:
}
}
</syntaxhighlight>
=={{header|Forth}}==
{{works with|GNU Forth}}
<
: read-lines
begin stdin pad max-line read-line throw
while pad swap \ addr len is the line of data, excluding newline
2drop
repeat ;</
=={{header|Fortran}}==
Line 1,405 ⟶ 1,435:
The code read line-by-line, but the maximum length of the line is limited (by a parameter)
<
implicit none
Line 1,424 ⟶ 1,454:
end if
end program BasicInputLoop</
=={{header|FreeBASIC}}==
<
Dim line_ As String ' line is a keyword
Line 1,440 ⟶ 1,470:
Print
Print "Press any key to quit"
Sleep</
=={{header|Frink}}==
<
println[line]
</syntaxhighlight>
=={{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.
<
local fn ReadTextFile
CFStringRef string
url = openpanel 1, @"Select text file..."
if ( url )
string = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
end if
else
// user cancelled
end if
end fn
fn ReadTextFile
HandleEvents</syntaxhighlight>
=={{header|GDScript}}==
{{works with|Godot|4.0.1}}
<syntaxhighlight lang="gdscript">
extends MainLoop
func _process(_delta: float) -> bool:
while true:
# Read a line from stdin
var input: String = OS.read_string_from_stdin()
# Empty lines are "\n" whereas end of input will be completely empty.
if len(input) == 0:
break
printraw(input)
return true # Exit
</syntaxhighlight>
=={{header|gnuplot}}==
The following gnuplot script echoes standard input
to standard output line-by-line until the end of the stream.
<syntaxhighlight lang
It makes use of the ability of gnuplot to spawn shell commands.
In that sense it might be considered cheating.
Line 1,492 ⟶ 1,532:
=={{header|Go}}==
The following reads a line at a time from stdin.
<
import (
Line 1,517 ⟶ 1,557:
_ = s
}
}</
Or, using <code>bufio.Scanner</code> you can read
line at a time,
Line 1,523 ⟶ 1,563:
byte or Unicode code point at a time,
or by any custom "split function".
<
import (
Line 1,546 ⟶ 1,586:
log.Fatal(err)
}
}</
=={{header|Groovy}}==
Solution:
<
System.in.eachLine { line, i ->
lineMap[i] = line
}
lineMap.each { println it }</
{{out|Test}}
Line 1,580 ⟶ 1,620:
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.
<
readLines :: Handle -> IO [String]
Line 1,590 ⟶ 1,630:
readWords h = do
s <- hGetContents h
return $ words s</
=={{header|HicEst}}==
<
OPEN(FIle=name, OLD, LENgth=bytes, IOStat=errorcode, ERror=9)
Line 1,602 ⟶ 1,642:
ENDDO
9 WRITE(Messagebox, Name) line, errorcode</
=={{header|i}}==
<
loop {
read()
Line 1,612 ⟶ 1,652:
}
}
}</
=={{header|Icon}} and {{header|Unicon}}==
<
# call either words or lines depending on what you want to do.
procedure main()
Line 1,628 ⟶ 1,668:
local line
while line := read() do line ? every write(str2toks())
end</
{{libheader|Icon Programming Library}}
See [http://www.cs.arizona.edu/icon/library/src/procs/str2toks.icn str2toks]
Line 1,634 ⟶ 1,674:
=={{header|J}}==
Script "read-input-until-eof.ijs":
<syntaxhighlight lang
NB. read input until EOF
((1!:1) 3)(1!:2) 4 NB. tested under j602
exit ''</
Example:
<
> abc
> def
Line 1,648 ⟶ 1,688:
def
ghi
now is the time for all good men ...</
=={{header|Java}}==
Some people prefer <tt>Scanner</tt> or <tt>BufferedReader</tt>, so a way with each is presented.
<
import java.util.Scanner;
Line 1,676 ⟶ 1,716:
}
}
}</
Or
<
import java.io.IOException;
import java.io.InputStreamReader;
Line 1,708 ⟶ 1,748:
}
}
}</
=={{header|JavaScript}}==
Line 1,720 ⟶ 1,760:
As above, this operates on standard input
<
var i = 0;
Line 1,727 ⟶ 1,767:
// do something with line
WScript.echo(++i + ": " + line);
}</
=={{header|jq}}==
Line 1,734 ⟶ 1,774:
.
For example, to echo each line of text in a file, one could invoke jq as follows:<
</syntaxhighlight>
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
Other options, e.g. to emit JSON in compact form, also exist.
=={{header|Jsish}}==
<
var line;
Line 1,749 ⟶ 1,789:
while (line = console.input()) { cs += line.length; ls += 1; }
printf("%d lines, %d characters\n", ls, cs);</
{{out}}
Line 1,758 ⟶ 1,798:
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.
<
while !eof(stream)
line = readline(stream)
println(line)
end</
{{Out}}
<pre>1
Line 1,773 ⟶ 1,813:
=={{header|Kotlin}}==
<
import java.util.*
Line 1,789 ⟶ 1,829:
words.add(input)
}
}</
Sample input/output:
{{out}}
Line 1,811 ⟶ 1,851:
=={{header|Lang5}}==
<
: ==>contents
'< swap open 'fh set fh fin read-lines fh close ;
'file.txt ==>contents</
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">
local(
myfile = file('//path/to/file.txt'),
Line 1,828 ⟶ 1,868:
}
#textresult -> join('<br />')</
Result:
Line 1,836 ⟶ 1,876:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
filedialog "Open","*.txt",file$
if file$="" then end
Line 1,845 ⟶ 1,885:
wend
close #f
end </
=={{header|LIL}}==
From the canread.lil sample that ships with LIL.
<
# canread test (note that canread is not available in LIL/FPLIL itself
# but provided by the command line interfaces in main.c/lil.pas)
Line 1,867 ⟶ 1,907:
inc count
}
print $count lines</
{{out}}
Line 1,878 ⟶ 1,918:
* 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
<
=={{header|LSL}}==
Line 1,884 ⟶ 1,924:
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.)
<
default {
integer iNotecardLine = 0;
Line 1,899 ⟶ 1,939:
}
}
}</
{{out}}
<pre>Reading 'Input_Loop_Data_Source.txt'
Line 1,921 ⟶ 1,961:
=={{header|Lua}}==
<
str = io.read()
while str do
table.insert(lines,str)
str = io.read()
end</
=== 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.
<
for line in io.lines() do
table.insert(lines, line) -- add the line to the list of lines
end</
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Document A$={1st Line
2nd line
Line 1,962 ⟶ 2,002:
\\ List of current variables (in any scope, public only)
List
</syntaxhighlight>
=={{header|Maple}}==
<syntaxhighlight lang="maple">
readinput:=proc(filename)
local line,file;
Line 1,975 ⟶ 2,015:
end do;
end proc;
</syntaxhighlight>
=={{header|MACRO-10}}==
<syntaxhighlight lang="macro-10">
TITLE Input Loop
Line 2,097 ⟶ 2,137:
END GO
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
While[a != EndOfFile, Read[stream, Word]];
Close[stream]</
=={{header|MAXScript}}==
this function will read a file line by line.
<
(
local in_file = openfile FileName
Line 2,115 ⟶ 2,155:
)
close in_file
)</
=={{header|Mercury}}==
<syntaxhighlight lang="text">
:- module input_loop.
:- interface.
Line 2,150 ⟶ 2,190:
io.set_exit_status(1, !IO)
).
</syntaxhighlight>
=={{header|mIRC Scripting Language}}==
<
while (%n <= $lines(input.txt)) {
write output.txt $read(input.txt,%n)
inc %n
}</
=={{header|ML/I}}==
The very nature of ML/I is that its default behaviour
is to copy from input to output until it reaches end of file.
=={{header|Modula-2}}==
<
VAR n : CARDINAL;
Line 2,187 ⟶ 2,226:
IF n <= HIGH (str) THEN str [n-1] := 0C END;
lastCh := ch
END ReadName;</
=={{header|Modula-3}}==
<
IMPORT Rd, Wr, Stdio;
Line 2,203 ⟶ 2,242:
Wr.PutText(Stdio.stdout, buf);
END;
END Output.</
=={{header|NetRexx}}==
=== Using NetRexx <tt>ASK</tt> Special Variable ===
<
options replace format comments java crossref symbols nobinary
Line 2,228 ⟶ 2,267:
return
</syntaxhighlight>
=== Using Java <tt>Scanner</tt> ===
<
options replace format comments java crossref symbols nobinary
Line 2,251 ⟶ 2,290:
return
</syntaxhighlight>
=={{header|Nim}}==
Read from stdin until end of data has been reached:
<
while stdin.readLine(line):
echo line</
Choose splitting string:
<
var lines = stdin.readAll()
for line in lines.split("\n"):
echo line</
Read from a known text file:
<
for line in i.lines:
discard # process line
i.close()</
Another, shorter, way to do this:
<
discard # process line</
=={{header|NodeJS}}==
<syntaxhighlight lang="nodejs">
#!/usr/bin/env node
const EventEmitter = require('events');
function stdinLineByLine() {
const stdin = new EventEmitter();
let buff = '';
process.stdin
.on('data', data => {
buff += data;
lines = buff.split(/\r\n|\n/);
buff = lines.pop();
lines.forEach(line => stdin.emit('line', line));
})
.on('end', () => {
if (buff.length > 0) stdin.emit('line', buff);
});
return stdin;
}
const stdin = stdinLineByLine();
stdin.on('line', console.log);
</syntaxhighlight>
=={{header|Oberon-2}}==
Works with oo2c Version 2
<
MODULE InputLoop;
IMPORT
Line 2,296 ⟶ 2,363:
END
END InputLoop.
</syntaxhighlight>
Execute: InputLoop < Inputloop.Mod<br/>
Output:
Line 2,321 ⟶ 2,388:
=={{header|Objeck}}==
<
use IO;
Line 2,339 ⟶ 2,406:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
<
try
let line = input_line ic in
line :: read_lines ic
with End_of_file ->
[]</
The version above will work for small files, but it is not tail-recursive. <br />
Below will be more scalable:
<
try Some (input_line ic)
with End_of_file -> None
Line 2,357 ⟶ 2,425:
let read_lines ic =
let rec loop acc =
match
| Some line -> loop (line :: acc)
| None -> (List.rev acc)
in
loop []
;;</
Or with a higher order function:
<
let rec loop () =
try f (input_line ic); loop ()
with End_of_file -> ()
in
loop ()
let () =
let ic = open_in Sys.argv.(1) in
read_lines print_endline ic</syntaxhighlight>
=={{header|Oforth}}==
Line 2,389 ⟶ 2,449:
Reads a file line by line and write each line on standard output :
<
=={{header|Oz}}==
<
%% Text: an instance of Open.text (a mixin class)
fun {ReadAll Text}
Line 2,398 ⟶ 2,458:
[] Line then Line|{ReadAll Text}
end
end</
=={{header|Pascal}}==
<
var
Line 2,433 ⟶ 2,493:
closefile(f);
end;</
=={{header|Perl}}==
The angle brackets operator ( <tt><...></tt> ) reads one line at a time from a filehandle in scalar context:
<
while (my $line = <FH>) {
chomp $line; # removes trailing newline
# process $line
}
close FH or die "can't close file: $!";</
Or you can get a list of all lines when you use it in list context:
<
Or a simpler program for lines of files entered as command line arguments or standard input:
<
# $_ contains a line
}</
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,470 ⟶ 2,530:
{{trans|Euphoria}}
Process text stream line-by-line:
<!--<
<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>
Line 2,482 ⟶ 2,542:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<!--</
=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Input_loop
by Galileo, 10/2022 #/
include ..\Utilitys.pmt
def eof? dup -1 == enddef
"input.txt" "r" fopen
( inf 0 -1 ) for drop
dup fgets eof? if drop exitfor else print endif
endfor
fclose
"input.txt" "r" fopen
eof? not while
dup fgets eof? if drop false else print true endif
endwhile
fclose</syntaxhighlight>
=={{header|PHP}}==
<
if ($fh) {
while (!feof($fh)) {
Line 2,492 ⟶ 2,573:
}
fclose($fh);
}</
Or you can get an array of all the lines in the file:
<
Or you can get the entire file as a string:
<
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
Reader = open("file.txt"),
while(not at_end_of_stream(Reader))
L = read_line(Reader),
println(L)
end,
close(Reader).</syntaxhighlight>
=={{header|PicoLisp}}==
This reads all lines in a file, and returns them as a list of lists
<
(make
(until (eof)
(link (line)) ) ) )</
=={{header|PL/I}}==
<
open file (in) title ('/TEXT.DAT,type(text),recsize(200)' );
Line 2,516 ⟶ 2,607:
get file(in) edit (line) (L);
put skip list (line);
end;</
=={{header|PowerShell}}==
<
ForEach-Object {
$_
}</
or
<
=={{header|PureBasic}}==
File objects can be read bytewise, characterwise (ASCII or UNICODE), floatwise, doublewise, integerwise, linewise ...
<
; file based line wise
If ReadFile(0, "Text.txt")
Line 2,544 ⟶ 2,635:
CloseFile(1)
EndIf
EndIf</
=={{header|Python}}==
Line 2,550 ⟶ 2,641:
To create a Python3 input loop use python's `input()` function.
<
x = input("What is your age? ")
print(x)</
Python file objects can be iterated like lists:
<
try:
for line in my_file:
pass # process line, includes newline
finally:
my_file.close()</
One can open a new stream for read and have it automatically close when done, with a new "with" statement:
<
with open(filename, 'r') as f:
for line in f:
pass # process line, includes newline</
You can also get lines manually from a file:
<
lines = my_file.readlines() # returns a list of the rest of the lines from the file</
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:
<
for line in fileinput.input():
pass # process line, includes newline</
The fileinput module can also do inplace file editing, follow line counts, and the name of the current file being read etc.
=={{header|R}}==
Note that read.csv and read.table provide alternatives for files with 'dataset' style contents.
<
=={{header|Racket}}==
The following prints input lines from standard input to standard output:
<
#lang racket
(copy-port (current-input-port) (current-output-port))
</syntaxhighlight>
=={{header|Rapira}}==
<syntaxhighlight lang="rapira">while 1 do
input text: str
output: str
od</syntaxhighlight>
=={{header|Raku}}==
Line 2,601 ⟶ 2,698:
'''Line-by-line''' <small>''(line endings are automatically stripped)''</small>
*From a file:<syntaxhighlight lang="raku"
...
}</
*From standard input:<syntaxhighlight lang="raku"
...
}</
*From a pipe:<syntaxhighlight lang="raku"
...
}</
*From a pipe, with custom line separator <small>''(in this example to handle filenames containing newlines)''</small>:<syntaxhighlight lang="raku"
...
}</
'''Word-by-word'''
*From a file <syntaxhighlight lang="raku"
...
}</
*From standard input or a pipe, accordingly.
=={{header|REBOL}}==
<
Title: "Basic Input Loop"
URL: http://rosettacode.org/wiki/Basic_input_loop
Line 2,641 ⟶ 2,738:
f: next f ; Advance to next line.
]
close f</
=={{header|REXX}}==
Line 2,647 ⟶ 2,744:
{{works with|oorexx and Regina}}
Reading line by line from the standard input using <tt>linein</tt> and <tt>lines</tt> did not work.
<
call charout ,charin(stdin)
end</
===version 1b===
{{works with|oorexx and Regina}}
Apparently only lines() does not work
<
input=linein(stdin)
Call lineout ,input
End</
===version 2===
{{works with|ARexx}}
<
do until eof(stdin)
l = readln(stdin)
say l
end</
===version 3===
Line 2,671 ⟶ 2,768:
Therefore, the following two REXX programs use the presence of a null line to indicate e-o-f.
<
do until _==''
parse pull _
end /*until*/ /*stick a fork in it, we're done.*/</
===version 4===
<
do until _==''
_= linein()
end /*until*/ /*stick a fork in it, we're done.*/</
=={{header|Ring}}==
<
fp = fopen("C:\Ring\ReadMe.txt","r")
Line 2,694 ⟶ 2,791:
fclose(fp)
</syntaxhighlight>
=={{header|Ruby}}==
Ruby input streams are IO objects. One can use IO#each or IO#each_line to iterate lines from a stream.
<
stream.each do |line|
# process line
end</
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.
<
ary = stream.map {|line| line.chomp.length}</
''To open a new stream for reading, see [[Read a file line by line#Ruby]].''
=={{header|Run BASIC}}==
<
while not(eof(#f))
line input #f, a$
print a$
wend
close #f</
=={{header|Rust}}==
<
use std::fs::File;
Line 2,738 ⟶ 2,835:
}
Ok(())
}</
=={{header|Scala}}==
{{libheader|Scala}}
{{works with|Scala|2.10.3}}
<
line => ... }</
=={{header|sed}}==
Line 2,767 ⟶ 2,864:
=={{header|Seed7}}==
<
const proc: main is func
Line 2,777 ⟶ 2,874:
writeln("LINE: " <& line);
end while;
end func;</
=={{header|Sidef}}==
To read from the standard input, you can use '''STDIN''' as your '''fh'''.
<
file.open_r(\var fh, \var err) || die "#{file}: #{err}"
Line 2,788 ⟶ 2,885:
say word
}
}</
=={{header|Slate}}==
<
=={{header|Smalltalk}}==
<
f := FileStream open: 'afile.txt' mode: FileStream read.
[ f atEnd ] whileFalse: [ (f nextLine) displayNl ] .</
=={{header|SNOBOL4}}==
<
end</
=={{header|Sparkling}}==
<
while (line = getline()) != nil {
print(line);
}</
=={{header|Standard ML}}==
<
case TextIO.inputLine strm of
SOME line => foldLines f (f (line, init)) strm
| NONE => init</
Example: Output the lines from stdin in reverse order.
<
=={{header|Tcl}}==
<
while {[gets $fh line] != -1} {
# process $line
}
close $fh</
For “small” files, it is often more common to do this:
<
set data [read $fh]
close $fh
foreach line [split $data \n] {
# process line
}</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
file="a.txt"
Line 2,841 ⟶ 2,938:
ENDLOOP
ENDACCESS source
</syntaxhighlight>
=={{header|TypeScript}}==
<syntaxhighlight lang="typescript">
#!/usr/bin/env node
import EventEmitter from 'events';
function stdinLineByLine() {
const stdin = new EventEmitter();
let buff = '';
let lines;
process.stdin
.on('data', (data) => {
buff += data;
lines = buff.split(/\r\n|\n/);
buff = lines.pop();
lines.forEach((line) => stdin.emit('line', line));
})
.on('end', () => {
if (buff.length > 0) stdin.emit('line', buff);
});
return stdin;
}
const stdin = stdinLineByLine();
stdin.on('line', console.log);
</syntaxhighlight>
=={{header|UNIX Shell}}==
When there is something to do with the input, here is a loop:
<
# examine or do something to the text in the "line" variable
echo "$line"
done</
The following echoes standard input to standard output line-by-line until the end of the stream.
<
Since <code>cat</code> defaults to reading from standard input and writing to standard output, this can be further simplified to the following.
<syntaxhighlight lang
=={{header|UnixPipes}}==
Line 2,858 ⟶ 2,985:
read by lines:
<
read by words:
<
=={{header|Ursa}}==
<
f.open "filename.txt"
while (f.hasnext)
out (in string f) endl console
end while</
=={{header|Vala}}==
<
string? s;
while((s = stdin.read_line()) != null) {
Line 2,876 ⟶ 3,003:
}
return 0;
}</
=={{header|VBA}}==
<
Dim filesystem As Object, stream As Object, line As String
Set filesystem = CreateObject("Scripting.FileSystemObject")
Line 2,888 ⟶ 3,015:
Loop
stream.Close
End Sub</
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
filepath = "SPECIFY PATH TO TEXT FILE HERE"
Line 2,904 ⟶ 3,031:
objInFile.Close
Set objFSO = Nothing
</syntaxhighlight>
=={{header|Visual Basic .NET}}==
Line 2,910 ⟶ 3,037:
This reads a stream line by line, outputing each line to the screen.
<
Dim line = stream.ReadLine
Do Until line Is Nothing
Line 2,916 ⟶ 3,043:
line = stream.ReadLine
Loop
End Sub</
=={{header|V (Vlang)}}==
<syntaxhighlight lang="Zig">
import os
fn main() {
mut ay_view_content := []string{}
file := "./input.txt"
// check if file exists
if os.is_file(file) == false {
print("Error: '${file}' not found")
exit(-1)
}
ay_view_content << os.read_lines(file) or {print(err) exit(-2)}
for line in ay_view_content {
if line !="" {println(line)}
if line =="" {println("Found blank line!")}
}
}
</syntaxhighlight>
=={{header|Wren}}==
<
File.open("input.txt") { |file|
Line 2,938 ⟶ 3,085:
}
}
}</
=={{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.
<
#define SYS_OPEN $2
#define SYS_CLOSE $3
Line 3,091 ⟶ 3,238:
filesize: // 8 bytes.
.quad 0
.zero STATSIZE-FSIZEOFF+8</
=={{header|XPL0}}==
Text stream is a file redirected on command line i.e: <file.txt
<
[repeat \read file
repeat \read line
Line 3,103 ⟶ 3,250:
until C < $20; \CR, LF, or EOF
until C = \EOF\ $1A;
]</
=={{header|zkl}}==
Line 3,110 ⟶ 3,257:
Word by word isn't explicitly supported.
If an object is stream-able, it supports methods like foreach, pump, apply, reduce, etc.
<
List(1,2,3).readln() // here, a "line" is a list element
Utils.Helpers.zipWith(False, // enumerate a file
fcn(n,line){"%3d: %s".fmt(n,line).print()},[1..],File("cmp.zkl"))</
|