Input loop: Difference between revisions

20,017 bytes added ,  3 months ago
m
m (Fix Perl 6 -> Raku in comments)
imported>Arakov
 
(38 intermediate revisions by 25 users not shown)
Line 15:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program inputLoop64.s */
Line 176:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC ReadStream(BYTE stream)
CHAR ARRAY line(255)
 
WHILE Eof(stream)=0
DO
InputSD(stream,line)
PrintE(line)
OD
RETURN
 
PROC Main()
BYTE streamId=[1]
 
Close(streamId)
Open(streamId,"H6:INPUT_PU.ACT",4)
PrintE("Reading from stream...") PutE()
ReadStream(streamId)
Close(streamId)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Input_loop.png Screenshot from Atari 8-bit computer]
<pre>
Reading from stream...
 
PROC ReadStream(BYTE stream)
CHAR ARRAY line(255)
 
WHILE Eof(stream)=0
DO
InputSD(stream,line)
PrintE(line)
OD
RETURN
 
PROC Main()
BYTE streamId=[1]
 
Close(streamId)
Open(streamId,"H6:INPUT_PU.ACT",4)
PrintE("Reading from stream...") PutE()
ReadStream(streamId)
Close(streamId)
RETURN
</pre>
 
=={{header|Ada}}==
This example reads in a text stream from standard input line by line
and writes the output to standard output.
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
 
procedure Read_Stream is
Line 198 ⟶ 244:
end if;
end loop;
end Read_Stream;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
read_stream(file f)
{
Line 209 ⟶ 255:
# the read line available as -s-
}
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
For file consisting of just one page - a typical linux/unix file:
<langsyntaxhighlight lang="algol68">main:(
PROC raise logical file end = (REF FILE f) BOOL: ( except logical file end );
on logical file end(stand in, raise logical file end);
Line 223 ⟶ 269:
except logical file end:
SKIP
)</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="algol68">main:(
PROC raise logical file end = (REF FILE f) BOOL: ( except logical file end );
on logical file end(stand in, raise logical file end);
Line 242 ⟶ 288:
except logical file end:
SKIP
)</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang="algolw">begin
string(80) line;
% allow the program to continue after reaching end-of-file %
Line 257 ⟶ 303:
read( line )
end
end.</langsyntaxhighlight>
 
=={{header|AmigaE}}==
<langsyntaxhighlight lang="amigae">CONST BUFLEN=1024, EOF=-1
 
PROC consume_input(fh)
Line 285 ⟶ 331:
Close(fh)
ENDIF
ENDPROC</langsyntaxhighlight>
 
=={{header|APL}}==
{{works with|GNU APL}}
<syntaxhighlight lang="apl">
h ← ⊃ (⎕fio['read_text'] 'corpus/sample1.txt')
⍴h
7 49
]boxing 8
h
┌→────────────────────────────────────────────────┐
↓This is some sample text. │
│The text itself has multiple lines, and │
│the text has some words that occur multiple times│
│in the text. │
│ │
│This is the end of the text. │
│ │
└─────────────────────────────────────────────────┘
</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 437 ⟶ 502:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 454 ⟶ 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.
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop, Read, Input.txt, Output.txt
{
FileAppend, %A_LoopReadLine%`n
}</langsyntaxhighlight>
 
=={{header|AWK}}==
This just reads lines from stdin and prints them until EOF is read.
 
<syntaxhighlight lang ="awk">{ print $0 }</langsyntaxhighlight>
 
or, more idiomatic:
 
<syntaxhighlight lang ="awk">1</langsyntaxhighlight>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">f = freefile
open f, "test.txt"
 
while not eof(f)
linea$ = readline(f)
print linea$ # echo to the console
end while
close f
end</syntaxhighlight>
 
==={{header|OxygenBasic}}===
<syntaxhighlight lang="text">
uses Console
uses ParseUtil
string s=getfile "t.txt"
int le=len s
int i=1
while i<le
print GetNextLine(s,i) cr
wend
pause
</syntaxhighlight>
 
==={{header|QBasic}}===
{{works with|QBasic}}
{{works with|QuickBasic}}
<syntaxhighlight lang="qbasic">OPEN "test.txt" FOR INPUT AS #1
 
WHILE NOT EOF(1)
INPUT #1, linea$
PRINT linea$ ' echo to the console
WEND
 
CLOSE #1
END</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">OPEN #1: NAME "test.txt", ACCESS INPUT
 
DO
LINE INPUT #1: linea$
PRINT linea$ ! echo to the console
LOOP UNTIL END #1
 
CLOSE #1
END</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">filename$ = "test.txt"
f = open(filename$)
 
if not f error "Could not open '" + filename$ + "' for reading"
while(not eof(f))
line input #f linea$
print linea$ // echo to the console
wend
 
close f
end</syntaxhighlight>
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">100 INPUT "FILENAME:";F$
110 D$ = CHR$(4)
120 PRINT D$"VERIFY"F$
Line 488 ⟶ 620:
190 POKE 216,0
200 IF PEEK(222) <> 5 THEN RESUME
210 PRINT D$"CLOSE"F$</langsyntaxhighlight>
 
==={{header|BaCon}}===
 
<syntaxhighlight lang="freebasic">
'--- 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"
INPUT filename$
 
text$ = LOAD$(filename$)
SPLIT text$ BY NL$ TO TOK$ SIZE dim
i = 0
 
'---dynamic index the end of an array is always null terminated
WHILE (TOK$[i] ISNOT NULL)
PRINT TOK$[i]
INCR i
WEND
</syntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
This specifically relates to console input (stdin).
<langsyntaxhighlight lang="bbcbasic"> STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
SYS "GetStdHandle", STD_INPUT_HANDLE TO @hfile%(1)
Line 503 ⟶ 653:
INPUT A$
PRINT A$
UNTIL FALSE</langsyntaxhighlight>
 
==={{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.
 
<syntaxhighlight lang="commodorebasicv2">
10 rem input loop - rosetta code
11 rem open command channel, clear screen, switch to lower case
12 open 15,8,15
15 print chr$(147);chr$(14):f$=""
 
20 input "Enter filename";f$
25 if f$="" then end
 
30 open 5,8,5,f$+",s,r"
40 gosub 1000
50 if er=62 then print "That file is not found... Try again.":close 5:goto 20
60 if er<>0 then print "There was an unexpected error.":close 5:gosub 1100
 
70 get#5,a$
80 if st and 64 then close 5:close 15:end
90 print a$;:goto 70
 
1000 rem check command channel for error
1005 rem error number, error msg$, track number, sector number
1010 input#15,er,er$,tk,sc
1020 return
 
1100 rem print error
1110 print:print er;"- ";er$;" track:";tk;"sector:";sc
1120 return
</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Type.bas"
110 TEXT 80
120 INPUT PROMPT "File name: ":F$
Line 520 ⟶ 701:
220 PRINT EXSTRING$(EXTYPE)
230 END
240 END HANDLER</langsyntaxhighlight>
 
Alternate solution:
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Type.bas"
110 INPUT PROMPT "File name: ":F$
120 WHEN EXCEPTION USE IOERROR
Line 533 ⟶ 714:
180 PRINT EXSTRING$(EXTYPE)
190 CLOSE #1
200 END HANDLER</langsyntaxhighlight>
==={{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}}==
<langsyntaxhighlight lang="dos">
for /f %%i in (file.txt) do if %%i@ neq @ echo %%i
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="bracmat">( put$("This is
a three line
text","test.txt",NEW)
Line 568 ⟶ 772:
)
& (fil$(,SET,-1)|out$"file closed")
);</langsyntaxhighlight>
{{out}}
<pre>breakchar:SP, word 1:This
Line 581 ⟶ 785:
Reads arbitrarily long line each time and return a null-terminated string.
Caller is responsible for freeing the string.
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
 
Line 612 ⟶ 816:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">using System;
using System.IO;
 
Line 633 ⟶ 837:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
The following functions send the words resp. lines
to a generic output iterator.
<langsyntaxhighlight lang="cpp">
#include <istream>
#include <string>
Line 683 ⟶ 887:
}
 
</syntaxhighlight>
</lang>
 
An alternate way to read words or lines is to use istream iterators:
 
<langsyntaxhighlight lang="cpp">
template<class OutIt>
void read_words(std::istream& is, OutIt dest)
Line 714 ⟶ 918:
dest);
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(defn basic-input [fname]
(line-seq (java.io.BufferedReader. (java.io.FileReader. fname))))</langsyntaxhighlight>
 
=={{header|COBOL}}==
{{works with|GNU Cobol|2.0}}
{{works with|Visual COBOL}}
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. input-loop.
Line 755 ⟶ 959:
CLOSE in-stream
.
END PROGRAM input-loop.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun basic-input (filename)
(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))))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio;
 
Line 787 ⟶ 991:
line.writeln;
}
}</langsyntaxhighlight>
 
{{libheader|Tango}}
<langsyntaxhighlight lang="d">import tango.io.Console;
import tango.text.stream.LineIterator;
 
Line 797 ⟶ 1,001:
// do something with each line
}
}</langsyntaxhighlight>
{{libheader|Tango}}
<langsyntaxhighlight lang="d">import tango.io.Console;
import tango.text.stream.SimpleIterator;
 
Line 806 ⟶ 1,010:
// do something with each word
}
}</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight Delphilang="delphi">program InputLoop;
 
{$APPTYPE CONSOLE}
Line 827 ⟶ 1,031:
lReader.Free;
end;
end.</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">while /= :eof dup !read-line!stdin:
!print( "Read a line: " !decode!utf-8 swap )
drop
!print "End of file."</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">repeat
l$ = input
until error = 1
print l$
.</langsyntaxhighlight>
 
=={{header|Eiffel}}==
{{works with|Eiffel Studio|6.6}}
 
<syntaxhighlight lang="eiffel">
<lang Eiffel>
note
description : "{
Line 1,083 ⟶ 1,287:
 
end
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 46.x:
 
Using ReaderEnumerator
<langsyntaxhighlight lang="elena">import system'routines;
import system'io;
import extensions'routines;
Line 1,095 ⟶ 1,299:
public program()
{
ReaderEnumerator.new(File.assign:("file.txt")).forEach(printingLn)
}</langsyntaxhighlight>
Using loop statement
<langsyntaxhighlight lang="elena">import system'io;
public program()
{
using(var reader := File.assign:("file.txt").textreader())
{
while (reader.Available)
Line 1,109 ⟶ 1,313:
}
}
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def input_loop(stream) do
case IO.read(stream, :line) do
Line 1,123 ⟶ 1,327:
 
path = hd(System.argv)
File.open!(path, [:read], fn stream -> RC.input_loop(stream) end)</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(read_files).
-export([main/0]).
Line 1,134 ⟶ 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>
</lang>
 
=={{header|ERRE}}==
Line 1,160 ⟶ 1,364:
=={{header|Euphoria}}==
Process text stream line-by-line:
<langsyntaxhighlight Euphorialang="euphoria">procedure process_line_by_line(integer fn)
object line
while 1 do
Line 1,169 ⟶ 1,373:
-- process the line
end while
end procedure</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
Using a sequence expression:
<langsyntaxhighlight lang="fsharp">
let lines_of_file file =
seq { use stream = System.IO.File.OpenRead file
Line 1,179 ⟶ 1,383:
while not reader.EndOfStream do
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.
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">"file.txt" utf8 [ [ process-line ] each-line ] with-file-reader</langsyntaxhighlight>
 
=={{header|Fantom}}==
Line 1,189 ⟶ 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.
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,216 ⟶ 1,420:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
{{works with|GNU Forth}}
<langsyntaxhighlight lang="forth">4096 constant max-line
: read-lines
begin stdin pad max-line read-line throw
while pad swap \ addr len is the line of data, excluding newline
2drop
repeat ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 1,231 ⟶ 1,435:
The code read line-by-line, but the maximum length of the line is limited (by a parameter)
 
<langsyntaxhighlight lang="fortran">program BasicInputLoop
 
implicit none
Line 1,250 ⟶ 1,454:
end if
 
end program BasicInputLoop</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim line_ As String ' line is a keyword
Line 1,266 ⟶ 1,470:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">while (line = readStdin[]) != undef
println[line]
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="futurebasic">include "NSLog.incl"
include "ConsoleWindow"
 
local fn ReadTextFile
dim as CFURLRef fileRefurl
CFStringRef string
dim as Handle h
dim as CFStringRef cfStr : cfStr = NULL
url = openpanel 1, @"Select text file..."
dim as long fileLen
if ( url )
 
string = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
if ( files$( _CFURLRefOpen, "TEXT", "Select text file...", @fileRef ) )
open "i",if 2,( fileRefstring )
fileLen = lof NSLog( 2@"%@", 1 string)
end if
h = fn NewHandleClear( fileLen )
else
if ( h )
// user cancelled
read file 2, [h], fileLen
end if
close #2
cfStr = fn CFStringCreateWithBytes( _kCFAllocatorDefault, #[h], fn GetHandleSize(h), _kCFStringEncodingMacRoman, _false )
fn DisposeH( h )
end if
else
// User canceled
end if
 
fn HIViewSetText( sConsoleHITextView, cfStr )
CFRelease( cfStr )
end fn
 
fn ReadTextFile
 
</lang>
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 ="gnuplot">!cat</langsyntaxhighlight>
It makes use of the ability of gnuplot to spawn shell commands.
In that sense it might be considered cheating.
Line 1,318 ⟶ 1,532:
=={{header|Go}}==
The following reads a line at a time from stdin.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,343 ⟶ 1,557:
_ = s
}
}</langsyntaxhighlight>
Or, using <code>bufio.Scanner</code> you can read
line at a time,
Line 1,349 ⟶ 1,563:
byte or Unicode code point at a time,
or by any custom "split function".
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,372 ⟶ 1,586:
log.Fatal(err)
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def lineMap = [:]
System.in.eachLine { line, i ->
lineMap[i] = line
}
lineMap.each { println it }</langsyntaxhighlight>
 
{{out|Test}}
Line 1,406 ⟶ 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.
 
<langsyntaxhighlight lang="haskell">import System.IO
 
readLines :: Handle -> IO [String]
Line 1,416 ⟶ 1,630:
readWords h = do
s <- hGetContents h
return $ words s</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">CHARACTER name='myfile.txt', string*1000
 
OPEN(FIle=name, OLD, LENgth=bytes, IOStat=errorcode, ERror=9)
Line 1,428 ⟶ 1,642:
ENDDO
 
9 WRITE(Messagebox, Name) line, errorcode</langsyntaxhighlight>
 
=={{header|i}}==
<langsyntaxhighlight lang="i">software {
loop {
read()
Line 1,438 ⟶ 1,652:
}
}
}</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">link str2toks
# call either words or lines depending on what you want to do.
procedure main()
Line 1,454 ⟶ 1,668:
local line
while line := read() do line ? every write(str2toks())
end</langsyntaxhighlight>
{{libheader|Icon Programming Library}}
See [http://www.cs.arizona.edu/icon/library/src/procs/str2toks.icn str2toks]
Line 1,460 ⟶ 1,674:
=={{header|J}}==
Script "read-input-until-eof.ijs":
<syntaxhighlight lang J="j">#!/Applications/j602usr/bin/jconsoleijconsole
NB. read input until EOF
((1!:1) 3)(1!:2) 4 NB. tested under j602
exit ''</langsyntaxhighlight>
Example:
<langsyntaxhighlight Jlang="j">$ ./read-input-to-eof.ijs <<EOF
> abc
> def
Line 1,474 ⟶ 1,688:
def
ghi
now is the time for all good men ...</langsyntaxhighlight>
 
=={{header|Java}}==
Some people prefer <tt>Scanner</tt> or <tt>BufferedReader</tt>, so a way with each is presented.
<langsyntaxhighlight lang="java">import java.io.InputStream;
import java.util.Scanner;
 
Line 1,502 ⟶ 1,716:
}
}
}</langsyntaxhighlight>
Or
<langsyntaxhighlight lang="java">import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
Line 1,534 ⟶ 1,748:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,546 ⟶ 1,760:
 
As above, this operates on standard input
<langsyntaxhighlight lang="javascript">var text_stream = WScript.StdIn;
var i = 0;
 
Line 1,553 ⟶ 1,767:
// do something with line
WScript.echo(++i + ": " + line);
}</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,560 ⟶ 1,774:
.
 
For example, to echo each line of text in a file, one could invoke jq as follows:<langsyntaxhighlight 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: <syntaxhighlight lang ="jq">jq . FILENAME</langsyntaxhighlight>
 
Other options, e.g. to emit JSON in compact form, also exist.
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">/* Input loop in Jsish */
 
var line;
Line 1,575 ⟶ 1,789:
while (line = console.input()) { cs += line.length; ls += 1; }
 
printf("%d lines, %d characters\n", ls, cs);</langsyntaxhighlight>
 
{{out}}
Line 1,584 ⟶ 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.
<langsyntaxhighlight lang="julia">stream = IOBuffer("1\n2\n3\n4\n\n6")
 
while !eof(stream)
line = readline(stream)
println(line)
end</langsyntaxhighlight>
{{Out}}
<pre>1
Line 1,599 ⟶ 1,813:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1
 
import java.util.*
Line 1,615 ⟶ 1,829:
words.add(input)
}
}</langsyntaxhighlight>
Sample input/output:
{{out}}
Line 1,637 ⟶ 1,851:
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">: read-lines do read . "\n" . eof if break then loop ;
: ==>contents
'< swap open 'fh set fh fin read-lines fh close ;
 
'file.txt ==>contents</langsyntaxhighlight>
 
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">
<lang Lasso>
local(
myfile = file('//path/to/file.txt'),
Line 1,654 ⟶ 1,868:
}
 
#textresult -> join('<br />')</langsyntaxhighlight>
 
Result:
Line 1,662 ⟶ 1,876:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
filedialog "Open","*.txt",file$
if file$="" then end
Line 1,671 ⟶ 1,885:
wend
close #f
end </langsyntaxhighlight>
 
=={{header|LIL}}==
From the canread.lil sample that ships with LIL.
 
<langsyntaxhighlight lang="tcl">#
# 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,693 ⟶ 1,907:
inc count
}
print $count lines</langsyntaxhighlight>
 
{{out}}
Line 1,704 ⟶ 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
<langsyntaxhighlight lang="logo">while [not eof?] [print readline]</langsyntaxhighlight>
 
=={{header|LSL}}==
Line 1,710 ⟶ 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.)
<langsyntaxhighlight LSLlang="lsl">string sNOTECARD = "Input_Loop_Data_Source.txt";
default {
integer iNotecardLine = 0;
Line 1,725 ⟶ 1,939:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Reading 'Input_Loop_Data_Source.txt'
Line 1,747 ⟶ 1,961:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">lines = {}
str = io.read()
while str do
table.insert(lines,str)
str = io.read()
end</langsyntaxhighlight>
 
=== 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.
 
<langsyntaxhighlight lang="lua">lines = {}
 
for line in io.lines() do
table.insert(lines, line) -- add the line to the list of lines
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Document A$={1st Line
2nd line
Line 1,788 ⟶ 2,002:
\\ List of current variables (in any scope, public only)
List
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
readinput:=proc(filename)
local line,file;
Line 1,801 ⟶ 2,015:
end do;
end proc;
</syntaxhighlight>
</lang>
 
=={{header|MACRO-10}}==
<syntaxhighlight lang="macro-10">
TITLE Input Loop
 
COMMENT !
Input-loop example, PDP-10 assembly language, kjx 2022.
Assembler: MACRO-10 Operating system: TOPS-20
 
This program opens the file "test.txt" and prints it's contents.
Note that the PDP-10 is a word-addressable machine with 36bit words,
and text-files use 7bit ASCII. That means one word fits 5 characters
and the buffer length of 20 (octal!) makes room for 80 (decimal) char-
acters.
The system-call used, SIN%, can also read until a specific character
(like CR) is seen, so reading one-line-at-a-time is also possible with
minimal changes.
!
 
SEARCH MONSYM,MACSYM
.REQUIRE SYS:MACREL
 
STDAC. ;Define standard register names.
 
;;
;; Buffers and data:
;;
 
PDLLEN==20
PDL: BLOCK PDLLEN ;Callstack (for ERCAL later).
 
MAXBUF==20 ;Use 20 36bit words for buffer.
MAXCHR==MAXBUF*5 ;One 36bit words fits 5 7bit bytes.
IN.BUF: BLOCK MAXBUF ;Buffer for lines read from file.
 
IN.JFN: BLOCK 1 ;Space for file-descriptor (JFN)
 
;;
;; Execution begins here:
;;
 
GO:: RESET% ;Initialize process.
MOVE P,[IOWD PDLLEN,PDL] ;Initialize stack.
;;
;; To open a file, we first have to get a file-handle (JFN):
;;
 
MOVX T1,GJ%OLD+GJ%SHT ;Flags go into T1:
; GJ%OLD = File already exists.
; GJ%SHT = Short system call.
HRROI T2,[ASCIZ /test.txt/] ;File name goes to T2.
GTJFN% ;Get a JFN for this file.
ERJMPS ERROR ; On error jump to ERROR.
MOVEM T1,IN.JFN ;Save the JFN.
;;
;; Now we can open the file:
;;
HRRZ T1,IN.JFN ;Right half-word of JFN into T1 +
;zero out left half to get rid of
;flags returned by GTJFN%.
MOVX T2,FLD(7,OF%BSZ)+OF%RD ;7bit characters, read-only.
OPENF% ;Open file.
ERJMPS ERROR ; On error jump to ERROR.
 
;;
;; Now we're reading MAXCHR 7bit bytes from that file
;; into IN.BUF and print that. If we'll see EOF, Q1 is
;; set to 1, and the loop is exited.
;;
SETZ Q1 ;Clear Q1 (we use that as an EOF marker)
DO.
MOVE T1,IN.JFN ;Read from IN.JFN (opened file)
HRROI T2,IN.BUF ;and write into IN.BUF.
MOVNI T3,MAXCHR ;Read maximum of MAXCHR characters.
SIN% ;Read string from file.
ERCAL [ MOVE T1,IN.JFN ; Error occured...
GTSTS% ; Get file status.
TXNN T2,GS%EOF ; End-of-file reached?
JRST ERROR ; No: Something else happened...
MOVEI Q1,1 ; Yes: Set Q1 to 1.
RET ] ; Continue.
MOVEI T1,.PRIOU ;Write to standard output.
HRROI T2,IN.BUF ;Buffer to write.
ADDI T3,MAXCHR ;Substract chars read from
MOVN T3,T3 ;maximum buffer length.
SOUT% ;Print string.
CAIN Q1,1 ;Is Q1 == 1?
JRST ENDPRG ; Yes: EOF was found above.
LOOP. ;Q1 is 0, so no EOF, continue.
ENDDO.
;;
;; ENDPRG: Close file and halt.
;;
ENDPRG: HRRZ T1,IN.JFN ;Put JFN into T1.
CLOSF% ;Close that file.
ERJMPS ERROR ; Go print error-msgs on error.
HALTF% ;Halt program.
JRST GO ;Allow for 'continue'-command.
 
;;
;; ERROR: Print standardized error-message and halt.
;;
 
ERROR: MOVEI T1,.PRIOU ;Print error on terminal (.PRIOU)
MOVE T2,[.FHSLF,,-1] ;Own process, most recent error.
SETZ T3, ;No limit on size of message.
ERSTR% ;Print that error message.
JFCL ; Ignore errors from ERSTR.
JFCL ; dito.
HALTF% ;Stop program.
JRST GO ;Allow for continuation.
 
END GO
</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">stream = OpenRead["file.txt"];
While[a != EndOfFile, Read[stream, Word]];
Close[stream]</langsyntaxhighlight>
 
=={{header|MAXScript}}==
this function will read a file line by line.
<langsyntaxhighlight MAXScriptlang="maxscript">fn ReadAFile FileName =
(
local in_file = openfile FileName
Line 1,819 ⟶ 2,155:
)
close in_file
)</langsyntaxhighlight>
 
=={{header|Mercury}}==
<syntaxhighlight lang="text">
:- module input_loop.
:- interface.
Line 1,854 ⟶ 2,190:
io.set_exit_status(1, !IO)
).
</syntaxhighlight>
</lang>
 
=={{header|mIRC Scripting Language}}==
<langsyntaxhighlight lang="mirc">var %n = 1
while (%n <= $lines(input.txt)) {
write output.txt $read(input.txt,%n)
inc %n
}</langsyntaxhighlight>
 
=={{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.
<lang ML/I></lang>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">PROCEDURE ReadName (VAR str : ARRAY OF CHAR);
 
VAR n : CARDINAL;
Line 1,891 ⟶ 2,226:
IF n <= HIGH (str) THEN str [n-1] := 0C END;
lastCh := ch
END ReadName;</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE Output EXPORTS Main;
 
IMPORT Rd, Wr, Stdio;
Line 1,907 ⟶ 2,242:
Wr.PutText(Stdio.stdout, buf);
END;
END Output.</langsyntaxhighlight>
 
=={{header|NetRexx}}==
=== Using NetRexx <tt>ASK</tt> Special Variable ===
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,932 ⟶ 2,267:
 
return
</syntaxhighlight>
</lang>
 
=== Using Java <tt>Scanner</tt> ===
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,955 ⟶ 2,290:
 
return
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
Read from stdin until end of data has been reached:
<lang nim>var i = open("input.txt")
<syntaxhighlight lang="nim">var line = ""
while stdin.readLine(line):
echo line</syntaxhighlight>
Choose splitting string:
<syntaxhighlight lang="nim">import strutils
 
var lines = stdin.readAll()
for line in lines.split("\n"):
echo line</syntaxhighlight>
 
Read from a known text file:
<syntaxhighlight lang="nim">var i = open("input.txt")
for line in i.lines:
discard # process line
i.close()</langsyntaxhighlight>
 
Another, shorter, way to do this:
<syntaxhighlight lang="nim">for line in "input.text".lines:
discard # process line</syntaxhighlight>
 
=={{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
<langsyntaxhighlight lang="oberon2">
MODULE InputLoop;
IMPORT
Line 1,984 ⟶ 2,363:
END
END InputLoop.
</syntaxhighlight>
</lang>
Execute: InputLoop &lt; Inputloop.Mod<br/>
Output:
Line 2,009 ⟶ 2,388:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use IO;
 
Line 2,027 ⟶ 2,406:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
<langsyntaxhighlight 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
with End_of_file ->
[]</langsyntaxhighlight>
 
The version above will work for small files, but it is not tail-recursive. <br />
Below will be more scalable:
 
<langsyntaxhighlight lang="ocaml">let read_lineread_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
Line 2,045 ⟶ 2,425:
let read_lines ic =
let rec loop acc =
match read_lineread_line_opt ic with
| Some line -> loop (line :: acc)
| None -> (List.rev acc)
in
loop []
;;</langsyntaxhighlight>
 
Or with a higher order function:
 
<langsyntaxhighlight lang="ocaml">let read_lines f ic =
let rec loop () =
try f (input_line ic); loop ()
with End_of_file -> ()
in
loop ()
 
let () =
read_lines print_endline (open_in Sys.argv.(1))</lang>
let ic = open_in Sys.argv.(1) in
 
read_lines print_endline ic</syntaxhighlight>
This function will apply your_function() to every line of input
<lang ocaml>
let rec input_caller () =
let input = read_line() in
your_function input ;
input_caller() ;
;;
 
let () = input_caller()</lang>
 
=={{header|Oforth}}==
Line 2,077 ⟶ 2,449:
Reads a file line by line and write each line on standard output :
 
<langsyntaxhighlight Oforthlang="oforth">: readFile(filename) File new(filename) apply(#println) ; </langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">%% Returns a list of lines.
%% Text: an instance of Open.text (a mixin class)
fun {ReadAll Text}
Line 2,086 ⟶ 2,458:
[] Line then Line|{ReadAll Text}
end
end</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">{ for stdio }
 
var
Line 2,121 ⟶ 2,493:
closefile(f);
 
end;</langsyntaxhighlight>
 
=={{header|Perl}}==
The angle brackets operator ( <tt><...></tt> ) reads one line at a time from a filehandle in scalar context:
<langsyntaxhighlight lang="perl">open FH, "< $filename" or die "can't open file: $!";
while (my $line = <FH>) {
chomp $line; # removes trailing newline
# process $line
}
close FH or die "can't close file: $!";</langsyntaxhighlight>
 
Or you can get a list of all lines when you use it in list context:
<langsyntaxhighlight lang="perl">@lines = <FH>;</langsyntaxhighlight>
 
Or a simpler program for lines of files entered as command line arguments or standard input:
<langsyntaxhighlight lang="perl">while (<>) {
# $_ contains a line
}</langsyntaxhighlight>
 
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,158 ⟶ 2,530:
{{trans|Euphoria}}
Process text stream line-by-line:
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>procedure process_line_by_line(integer fn)
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
object line
<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>
while 1 do
<span style="color: #004080;">object</span> <span style="color: #000000;">line</span>
line = gets(fn)
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
if atom(line) then
<span style="color: #000000;">line</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">gets</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
exit
<span style="color: #008080;">if</span> <span style="color: #004080;">atom</span><span style="color: #0000FF;">(</span><span style="color: #000000;">line</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
end if
<span style="color: #008080;">exit</span>
-- process the line
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #000080;font-style:italic;">-- process the line</span>
end procedure</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<!--</syntaxhighlight>-->
 
=={{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}}==
<langsyntaxhighlight lang="php">$fh = fopen($filename, 'r');
if ($fh) {
while (!feof($fh)) {
Line 2,177 ⟶ 2,573:
}
fclose($fh);
}</langsyntaxhighlight>
 
Or you can get an array of all the lines in the file:
<langsyntaxhighlight lang="php">$lines = file($filename);</langsyntaxhighlight>
 
Or you can get the entire file as a string:
<langsyntaxhighlight lang="php">$contents = file_get_contents($filename);</langsyntaxhighlight>
 
=={{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
<langsyntaxhighlight PicoLisplang="picolisp">(in "file.txt"
(make
(until (eof)
(link (line)) ) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">declare line character (200) varying;
 
open file (in) title ('/TEXT.DAT,type(text),recsize(200)' );
Line 2,201 ⟶ 2,607:
get file(in) edit (line) (L);
put skip list (line);
end;</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight Powershelllang="powershell">Get-Content c:\file.txt |
ForEach-Object {
$_
}</langsyntaxhighlight>
or
<langsyntaxhighlight Powershelllang="powershell">ForEach-Object -inputobject (get-content c:\file.txt) {$_}</langsyntaxhighlight>
 
=={{header|PureBasic}}==
File objects can be read bytewise, characterwise (ASCII or UNICODE), floatwise, doublewise, integerwise, linewise ...
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
; file based line wise
If ReadFile(0, "Text.txt")
Line 2,229 ⟶ 2,635:
CloseFile(1)
EndIf
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
Line 2,235 ⟶ 2,641:
To create a Python3 input loop use python's `input()` function.
 
<langsyntaxhighlight lang="python">while(True):
x = input("What is your age? ")
print(x)</langsyntaxhighlight>
 
Python file objects can be iterated like lists:
 
<langsyntaxhighlight lang="python">my_file = open(filename, 'r')
try:
for line in my_file:
pass # process line, includes newline
finally:
my_file.close()</langsyntaxhighlight>
 
One can open a new stream for read and have it automatically close when done, with a new "with" statement:
<langsyntaxhighlight lang="python">#from __future__ import with_statement # is not needed in Python 3.6
 
with open(filename, 'r') as f:
for line in f:
pass # process line, includes newline</langsyntaxhighlight>
 
You can also get lines manually from a file:
<langsyntaxhighlight 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</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="python">import fileinput
for line in fileinput.input():
pass # process line, includes newline</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="rsplus">lines <- readLines("file.txt")</langsyntaxhighlight>
 
=={{header|Racket}}==
 
The following prints input lines from standard input to standard output:
<langsyntaxhighlight lang="racket">
#lang racket
(copy-port (current-input-port) (current-output-port))
</syntaxhighlight>
</lang>
 
=={{header|Rapira}}==
<syntaxhighlight lang="rapira">while 1 do
input text: str
output: str
od</syntaxhighlight>
 
=={{header|Raku}}==
Line 2,286 ⟶ 2,698:
'''Line-by-line''' <small>''(line endings are automatically stripped)''</small>
 
*From a file:<syntaxhighlight lang="raku" perl6line>for "filename.txt".IO.lines -> $line {
...
}</langsyntaxhighlight>
*From standard input:<syntaxhighlight lang="raku" perl6line>for $*IN.lines -> $line {
...
}</langsyntaxhighlight>
*From a pipe:<syntaxhighlight lang="raku" perl6line>for run(«find -iname *.txt», :out).out.lines -> $filename {
...
}</langsyntaxhighlight>
*From a pipe, with custom line separator <small>''(in this example to handle filenames containing newlines)''</small>:<syntaxhighlight lang="raku" perl6line>for run(«find -iname *.txt -print0», :nl«\0», :out).out.lines -> $filename {
...
}</langsyntaxhighlight>
 
'''Word-by-word'''
*From a file <syntaxhighlight lang="raku" perl6line>for "filename.txt".IO.words -> $word {
...
}</langsyntaxhighlight>
*From standard input or a pipe, accordingly.
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Basic Input Loop"
URL: http://rosettacode.org/wiki/Basic_input_loop
Line 2,326 ⟶ 2,738:
f: next f ; Advance to next line.
]
close f</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,332 ⟶ 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.
<langsyntaxhighlight lang="rexx">do while stream(stdin, "State") <> "NOTREADY"
call charout ,charin(stdin)
end</langsyntaxhighlight>
 
===version 1b===
{{works with|oorexx and Regina}}
Apparently only lines() does not work
<langsyntaxhighlight lang="rexx">Do Until input=''
input=linein(stdin)
Call lineout ,input
End</langsyntaxhighlight>
 
===version 2===
{{works with|ARexx}}
<langsyntaxhighlight lang="rexx">/* -- AREXX -- */
do until eof(stdin)
l = readln(stdin)
say l
end</langsyntaxhighlight>
 
===version 3===
Line 2,356 ⟶ 2,768:
 
Therefore, the following two REXX programs use the presence of a null line to indicate e-o-f.
<langsyntaxhighlight lang="rexx">/*REXX program reads from the (console) default input stream until null*/
do until _==''
parse pull _
end /*until*/ /*stick a fork in it, we're done.*/</langsyntaxhighlight>
 
===version 4===
<langsyntaxhighlight lang="rexx">/*REXX program reads from the (console) default input stream until null*/
do until _==''
_= linein()
end /*until*/ /*stick a fork in it, we're done.*/</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
fp = fopen("C:\Ring\ReadMe.txt","r")
 
Line 2,379 ⟶ 2,791:
fclose(fp)
 
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Ruby input streams are IO objects. One can use IO#each or IO#each_line to iterate lines from a stream.
 
<langsyntaxhighlight lang="ruby">stream = $stdin
stream.each do |line|
# process line
end</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="ruby"># Create an array of lengths of every line.
ary = stream.map {|line| line.chomp.length}</langsyntaxhighlight>
 
''To open a new stream for reading, see [[Read a file line by line#Ruby]].''
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">open "\testFile.txt" for input as #f
while not(eof(#f))
line input #f, a$
print a$
wend
close #f</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust"> use std::io::{self, BufReader, Read, BufRead};
use std::fs::File;
 
Line 2,423 ⟶ 2,835:
}
Ok(())
}</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
{{works with|Scala|2.10.3}}
<langsyntaxhighlight lang="scala"> scala.io.Source.fromFile("input.txt").getLines().foreach {
line => ... }</langsyntaxhighlight>
 
=={{header|sed}}==
Line 2,452 ⟶ 2,864:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const proc: main is func
Line 2,462 ⟶ 2,874:
writeln("LINE: " <& line);
end while;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
To read from the standard input, you can use '''STDIN''' as your '''fh'''.
<langsyntaxhighlight lang="ruby">var file = File(__FILE__)
file.open_r(\var fh, \var err) || die "#{file}: #{err}"
 
Line 2,473 ⟶ 2,885:
say word
}
}</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">(File newNamed: 'README') reader sessionDo: [| :input | input lines do: [| :line | inform: line]].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">|f|
f := FileStream open: 'afile.txt' mode: FileStream read.
[ f atEnd ] whileFalse: [ (f nextLine) displayNl ] .</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight lang="snobol">loop output = input :s(loop)
end</langsyntaxhighlight>
 
=={{header|Sparkling}}==
<langsyntaxhighlight lang="sparkling">var line;
while (line = getline()) != nil {
print(line);
}</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<syntaxhighlight lang="sml">fun foldLines f init strm =
case TextIO.inputLine strm of
SOME line => foldLines f (f (line, init)) strm
| NONE => init</syntaxhighlight>
Example: Output the lines from stdin in reverse order.
<syntaxhighlight lang="sml">val () = (print o foldLines op^ "") TextIO.stdIn</syntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set fh [open $filename]
while {[gets $fh line] != -1} {
# process $line
}
close $fh</langsyntaxhighlight>
For “small” files, it is often more common to do this:
<langsyntaxhighlight lang="tcl">set fh [open $filename]
set data [read $fh]
close $fh
foreach line [split $data \n] {
# process line
}</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
file="a.txt"
Line 2,518 ⟶ 2,938:
ENDLOOP
ENDACCESS source
</syntaxhighlight>
</lang>
 
=={{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:
<langsyntaxhighlight lang="bash">while read line ; do
# examine or do something to the text in the "line" variable
echo "$line"
done</langsyntaxhighlight>
The following echoes standard input to standard output line-by-line until the end of the stream.
<langsyntaxhighlight lang="bash">cat < /dev/stdin > /dev/stdout</langsyntaxhighlight>
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 ="bash">cat</langsyntaxhighlight>
 
=={{header|UnixPipes}}==
Line 2,535 ⟶ 2,985:
 
read by lines:
<langsyntaxhighlight lang="bash">yes 'A B C D ' | while read x ; do echo -$x- ; done</langsyntaxhighlight>
read by words:
<langsyntaxhighlight lang="bash">yes 'A B C D ' | while read -d\ a ; do echo -$a- ; done</langsyntaxhighlight>
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa">decl file f
f.open "filename.txt"
while (f.hasnext)
out (in string f) endl console
end while</langsyntaxhighlight>
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">int main() {
string? s;
while((s = stdin.read_line()) != null) {
Line 2,553 ⟶ 3,003:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Public Sub test()
Dim filesystem As Object, stream As Object, line As String
Set filesystem = CreateObject("Scripting.FileSystemObject")
Line 2,565 ⟶ 3,015:
Loop
stream.Close
End Sub</langsyntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
filepath = "SPECIFY PATH TO TEXT FILE HERE"
 
Line 2,581 ⟶ 3,031:
objInFile.Close
Set objFSO = Nothing
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic .NET}}==
Line 2,587 ⟶ 3,037:
This reads a stream line by line, outputing each line to the screen.
 
<langsyntaxhighlight lang="vbnet">Sub Consume(ByVal stream As IO.StreamReader)
Dim line = stream.ReadLine
Do Until line Is Nothing
Line 2,593 ⟶ 3,043:
line = stream.ReadLine
Loop
End Sub</langsyntaxhighlight>
 
=={{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}}==
<syntaxhighlight lang="wren">import "io" for File
 
File.open("input.txt") { |file|
var offset = 0
var line = ""
while(true) {
var b = file.readBytes(1, offset)
offset = offset + 1
if (b == "\n") {
// process 'line'
line = "" // reset line variable
} else if (b == "\r") { // Windows
// wait for following "\n"
} else if (b == "") { // end of stream
return
} else {
line = line + b
}
}
}</syntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="x86">#define SYS_WRITE $1
#define SYS_OPEN $2
#define SYS_CLOSE $3
Line 2,746 ⟶ 3,238:
filesize: // 8 bytes.
.quad 0
.zero STATSIZE-FSIZEOFF+8</langsyntaxhighlight>
 
=={{header|XPL0}}==
Text stream is a file redirected on command line i.e: <file.txt
<langsyntaxhighlight XPL0lang="xpl0">int C;
[repeat \read file
repeat \read line
Line 2,758 ⟶ 3,250:
until C < $20; \CR, LF, or EOF
until C = \EOF\ $1A;
]</langsyntaxhighlight>
 
=={{header|zkl}}==
Line 2,765 ⟶ 3,257:
Word by word isn't explicitly supported.
If an object is stream-able, it supports methods like foreach, pump, apply, reduce, etc.
<langsyntaxhighlight lang="zkl">foreach line in (File("foo.txt")){...}
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"))</langsyntaxhighlight>
Anonymous user