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