Read a file line by line: Difference between revisions
m
syntax highlighting fixup automation
Puppydrum64 (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
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()
Line 254:
Return
</syntaxhighlight>
=={{header|Ada}}==
{{works with|Ada 2005}}
line_by_line.adb:
<
procedure Line_By_Line is
Line 273:
Close (File);
end Line_By_Line;
</syntaxhighlight>
{{Out}}
Line 293:
=={{header|Aime}}==
<
text s;
Line 301:
o_text(s);
o_byte('\n');
}</
=={{header|ALGOL 68}}==
Line 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 327:
printf(($g(0)": "$, count, line fmt, line))
OD;
done: SKIP</
{{out}}
<pre style="height:15ex;overflow:scroll">
Line 354:
=={{header|APL}}==
<syntaxhighlight lang="apl">
⍝⍝ GNU APL Version
∇listFile fname ;fileHandle;maxLineLen;line
Line 376:
This is the end of the text.
</syntaxhighlight>
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
Line 399:
println
exit(0)
</syntaxhighlight>
{{out}}
<pre>
Line 413:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program readfile.s */
Line 698:
iMagicNumber: .int 0xCCCCCCCD
</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 727:
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 733:
'''One-liner:'''
<
'''Shorter:'''<br>
Line 740:
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 752:
{ 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 781:
==={{header|BaCon}}===
<
filename$ = "readlines.bac"
OPEN filename$ FOR READING AS fh
Line 790:
WEND
PRINT lines, " lines in ", filename$
CLOSE FILE fh</
{{out}}
Line 797:
==={{header|IS-BASIC}}===
<
110 OPEN #1:NAME$ ACCESS INPUT
120 COPY FROM #1 TO #0
130 CLOSE #1</
==={{header|Locomotive Basic}}===
<
20 WHILE NOT EOF
30 LINE INPUT#9,i$
40 PRINT i$
50 WEND</
==={{header|OxygenBasic}}===
The core function '''GetFile''' reads the whole file:
<
function getline(string s, int *i) as string
int sl=i, el=i
Line 848:
done:
print "Line count " c
</syntaxhighlight>
==={{header|QBasic}}===
{{works with|QBasic}}
{{works with|QuickBasic}}
<
filename$ = "file.txt"
Line 863:
WEND
CLOSE #f
END</
==={{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)
Line 874:
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 880:
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 886:
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}}==
<
filename$ = "file.txt"
Line 898:
end while
close f
end</
=={{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 911:
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 929:
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 942:
)
& (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 980:
return 0;
}</
===with getline===
<
#include <stdio.h>
Line 1,007:
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>
Line 1,086:
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 1,126:
}
}
}</
=={{header|C++}}==
{{works with|C++03 to C++17 }}
<
#include <string>
#include <iostream>
Line 1,147:
infile.close( ) ;
return 0 ;
}</
====using std::getline====
Line 1,160:
</pre>
<
#include <fstream>
#include <iostream>
Line 1,180:
}
std::cout << "finished" << std::endl;
}</
{{out}}
Line 1,195:
{{libheader|U++}}
<
using namespace Upp;
Line 1,204:
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}}==
<
po: stream := stream$primary_output()
Line 1,241:
stream$close(fstream)
end
end start_up</
=={{header|COBOL}}==
<
PROGRAM-ID. read-file-line-by-line.
Line 1,281:
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,366:
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
;
Line 1,408:
GOTO CLOS
CLOS, STOP</
=={{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,431:
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,445:
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
Line 1,452:
=={{header|Draco}}==
<
proc nonrec main() void:
/* first we need to declare a file buffer and an input channel */
Line 1,480:
/* finally, close the file */
close(in_ch)
corp</
=={{header|Elena}}==
ELENA 4.x :
<
import extensions;
import extensions'routines;
Line 1,491:
{
File.assign:"file.txt".forEachLine(printingLn)
}</
=={{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,519:
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,536:
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,551:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM LETTURA
Line 1,573:
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,591:
i += 1
end while
close(fn)</
{{out}}
Line 1,625:
(1) name the euphoria script file <B>readfile.ex</B> or whatever name you want to give it. Change this line "constant filename = cmd[2]" to "constant filename = cmd[<B>3</B>]" like the following code.
<
constant filename = cmd[3]
constant fn = open(filename,"r")
Line 1,639:
i += 1
end while
close(fn)</
From the command line run:
<
eui readfile.ex "File.txt"
</syntaxhighlight>
{{out}}
Line 1,660:
=={{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,675:
Reads each line from the file "data.txt".
<
class Main
{
Line 1,686:
}
}
</syntaxhighlight>
=={{header|Forth}}==
<
: third ( A b c -- A b c A )
Line 1,699:
while pad swap ( fileid c-addr u ) \ string excludes the newline
2drop
repeat 2drop ;</
=={{header|Fortran}}==
Line 1,714:
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,745:
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,751:
=={{header|FreeBASIC}}==
<
Open "input.txt" For Input As #1
Line 1,762:
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,783:
Wend
End</
=={{header|GAP}}==
<
local file, line, count;
file := InputTextFile(name);
Line 1,803:
# 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,828:
lines++
stdout.printf("%04d %s\n", lines, line)
line = file.read_line()</
{{out}}
Line 1,846:
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,884:
}
}
</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,950:
fmt.Println(string(line))
}
}</
;ReadString
In comparison, ReadString is a little quick and dirty, but is often good enough.
<
import (
Line 1,984:
}
}
}</
=={{header|Groovy}}==
<
println "processing line $lineNumber: $line"
}</
Line 1,995:
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 2,017:
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 2,050:
lines=: }.lines
r
)</
<
next__example''
this is line 1
next__example''
and this is line 2</
=={{header|Java}}==
<
import java.io.FileReader;
Line 2,097:
}
}
}</
{{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 2,111:
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 2,125:
}catch(IOException | SecurityException e){
//problem with the file
}</
=={{header|JavaScript}}==
<
var readFile = function(path) {
Line 2,134:
};
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 2,144:
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 2,169:
=={{header|Julia}}==
<
for line in eachline(f)
println("read line: ", line)
end
end</
=={{header|Kotlin}}==
<
import java.io.File
Line 2,182:
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 2,200:
print t$
wend
close #f</
Mac
<
if file$="" then end
open file$ for input as #f
Line 2,209:
print t$
wend
close #f </
Unix
<
if file$="" then end
open file$ for input as #f
Line 2,218:
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 2,232:
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 2,247:
close file tFile
put tLines
end readFileLineByLine</
=={{header|Logo}}==
Line 2,254:
* 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,265:
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,278:
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,332:
}
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}}==
<
If[strm=!=$Failed,
While[line=!=EndOfFile,
Line 2,349:
(*Do something*)
]];
Close[strm];</
=={{header|MATLAB}} / {{header|Octave}}==
Line 2,355:
The function fgetl() read lines from file:
<syntaxhighlight lang="matlab">
fid = fopen('foobar.txt','r');
if (fid < 0)
Line 2,365:
end;
fclose(fid)
end; </
=={{header|Maxima}}==
<
readfile(name) := block(
Line 2,375:
close(f),
v
)$</
=={{header|Mercury}}==
Basic version.
<
:- interface.
Line 2,417:
ReadLineResult = error(Error),
error(io.error_message(Error))
).</
Version using a stream fold.
<
:- interface.
Line 2,452:
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,512:
} catch a break;
}
</syntaxhighlight>
{{out}}
Line 2,533:
=={{header|NetRexx}}==
=== Using Java <tt>Scanner</tt> ===
<
options replace format comments java crossref symbols nobinary
Line 2,564:
return fileLines
</syntaxhighlight>
=== Using Java <tt>Reader</tt> ===
<
options replace format comments java crossref symbols nobinary
Line 2,613:
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,643:
}
}
</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,658:
Now to get the individual lines, break down the string:
<
=={{header|OCaml}}==
<
let ic = open_in "input.txt" in
try
Line 2,670:
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,690:
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|Oforth}}==
<
| line | File new(fileName) forEach: line [ line println ] ;</
=={{header|PARI/GP}}==
Line 2,707:
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,713:
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,736:
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,748:
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,762:
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,779:
The readline function can be used instead of < >:
<
while (readline $fh)
{ ... }
Line 2,785:
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}}
<!--<
<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>
Line 2,802:
<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>
<!--</
{{out}}
<pre>
Line 2,819:
=={{header|Phixmonti}}==
<
argument 1 get "r" fopen var f
Line 2,826:
while
f fgets number? if drop f fclose false else print true endif
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}}==
Line 2,847:
===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.
<
FD = open("unixdict.txt"),
while (not at_end_of_stream(FD))
Line 2,854:
end,
close(FD),
nl.</
===read_file_lines===
For reasonable sized files, <code>read_file_lines/1</code> is usually the way to go.
<
foreach(Line in read_file_lines("unixdict.txt"))
println(Line)
end.</
=={{header|PicoLisp}}==
<
(while (line)
(process @) ) )</
=={{header|PL/I}}==
<
read: procedure options (main);
declare line character (500) varying;
Line 2,880:
end;
end read;
</syntaxhighlight>
=={{header|PowerShell}}==
<
try {
do {
Line 2,893:
$reader.Close()
}
</syntaxhighlight>
=={{header|PureBasic}}==
<
If ReadFile(0, FileName$) ; use ReadFile instead of OpenFile to include read-only files
Line 2,905:
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,935:
(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,970:
input "Press enter to exit: ";a$
</syntaxhighlight>
=={{header|REXX}}==
Line 2,978:
<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,990:
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,998:
<br>It can also just show the last line.
<br>If appropriate, the program will show the total number of lines in the file.
<syntaxhighlight lang
{{out|output|text= when using the input of: <tt> 123456.TXT </tt>}}
<pre>
Line 3,077:
=== ARexx version ===
<
filename='file.txt'
contents=''
Line 3,088:
ELSE EXIT 20
CALL Close filehandle
EXIT 0</
=={{header|Ring}}==
<
fp = fopen("C:\Ring\ReadMe.txt","r")
r = ""
Line 3,100:
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 3,121:
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 3,133:
wend
close #f
</syntaxhighlight>
=={{header|Rust}}==
<
use std::fs::File;
Line 3,144:
println!("{}", line.unwrap());
}
}</
{{out}}
Line 3,152:
=={{header|Scala}}==
<
Source.fromFile("foobar.txt").getLines.foreach(println)</
=={{header|Scheme}}==
<
;(use-modules (ice-9 rdelim))
Line 3,162:
(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 3,188:
writeln("LINE: " <& line);
end while;
end func;</
The function [http://seed7.sourceforge.net/libraries/file.htm#hasNext%28in_file%29 hasNext]
Line 3,195:
=={{header|SenseTalk}}==
The simple way:
<
put it
end repeat
</syntaxhighlight>
The more traditional way:
<
open file myFile
Line 3,210:
end repeat
close file myFile</
=={{header|Sidef}}==
''FileHandle.each{}'' is lazy, allowing us to do this:
<
print line
}</
Same thing explicitly:
<
while (fh.readline(\var line)) {
print 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,251:
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,264:
fclose(f);
}</
=={{header|SPL}}==
<
> !#.eof(f)
#.output(#.readline(f))
<</
=={{header|Tcl}}==
<
while {[gets $f line] >= 0} {
# This loops over every line
puts ">>$line<<"
}
close $f</
=={{header|TorqueScript}}==
Line 3,284:
Read a file line by line:
<syntaxhighlight lang="torquescript">
//Create a file object
Line 3,307:
%f.delete();
</syntaxhighlight>
=={{header|Turing}}==
For a named file:
<
open : f, "rosetta.txt", get
loop
Line 3,319:
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,350:
ENDLOOP
ENDACCESS q
</syntaxhighlight>
or:
<
LOOP line=datei
PRINT line
ENDLOOP
</syntaxhighlight>
Line 3,362:
Taken from C++ U++ section
<
using namespace Upp;
Line 3,371:
while(in && !in.IsEof())
Cout().PutLine(in.GetLine());
}</
Line 3,381:
{{works with|Almquist Shell}}
<
# This loop is inside a pipeline; many shells will
# run this loop inside a subshell.
Line 3,387:
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,397:
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,410:
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,432:
}
}
</syntaxhighlight>
=={{header|VBA}}==
<
Sub Main()
Dim fInput As String, fOutput As String 'File names
Line 3,450:
Close #1
Close #2
End Sub 'Main</
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
FilePath = "<SPECIFY FILE PATH HERE>"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Line 3,462:
objFile.Close
Set objFSO = Nothing
</syntaxhighlight>
=={{header|Vedit macro language}}==
Line 3,471:
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,485:
}
Buf_Close(NOMSG) // close the input file
Buf_Switch(#11) // show the output </
{{out}}
Line 3,510:
===Simple version===
{{works with|Visual Basic|VB6 Standard}}
<
Sub Main()
Dim fInput As String, fOutput As String 'File names
Line 3,533:
InputError:
MsgBox "File: " & fInput & " not found"
End Sub 'Main</
===Complex version===
<
'
' (c) Copyright 1993 - 2011 Mark Hobley
Line 3,668:
Public Function btrim$(arg$)
btrim$ = LTrim$(RTrim$(arg$))
End Function</
=={{header|Visual Basic .NET}}==
<
' Loop through the lines of a file.
Line 3,687:
oReader.Close()
End Sub</
=={{header|Wart}}==
<
drain (read_line)</
=={{header|Wren}}==
<
var lines = [] // store lines read
Line 3,716:
}
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"));
...</
|