Read a file line by line: Difference between revisions
Content added Content deleted
Puppydrum64 (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 18: | Line 18: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
This program uses OS QSAM I/O macros (OPEN,CLOSE,GET,PUT,DCB). |
This program uses OS QSAM I/O macros (OPEN,CLOSE,GET,PUT,DCB). |
||
< |
<syntaxhighlight lang="360asm">* Read a file line by line 12/06/2016 |
||
READFILE CSECT |
READFILE CSECT |
||
SAVE (14,12) save registers on entry |
SAVE (14,12) save registers on entry |
||
Line 50: | Line 50: | ||
PG DS CL80 buffer |
PG DS CL80 buffer |
||
YREGS |
YREGS |
||
END READFILE</ |
END READFILE</syntaxhighlight> |
||
=={{header|8th}}== |
=={{header|8th}}== |
||
< |
<syntaxhighlight lang="forth"> |
||
"path/to/file" f:open ( . cr ) f:eachline f:close |
"path/to/file" f:open ( . cr ) f:eachline f:close |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |
||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
||
<syntaxhighlight lang="aarch64 assembly"> |
|||
<lang AArch64 Assembly> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
/* ARM assembly AARCH64 Raspberry PI 3B */ |
||
/* program readfile64.s */ |
/* program readfile64.s */ |
||
Line 238: | Line 238: | ||
/* for this file see task include a file in language AArch64 assembly */ |
/* for this file see task include a file in language AArch64 assembly */ |
||
.include "../includeARM64.inc" |
.include "../includeARM64.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
<lang>char array TXT |
<syntaxhighlight lang="text">char array TXT |
||
Proc Main() |
Proc Main() |
||
Line 254: | Line 254: | ||
Return |
Return |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
{{works with|Ada 2005}} |
{{works with|Ada 2005}} |
||
line_by_line.adb: |
line_by_line.adb: |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO; |
||
procedure Line_By_Line is |
procedure Line_By_Line is |
||
Line 273: | Line 273: | ||
Close (File); |
Close (File); |
||
end Line_By_Line; |
end Line_By_Line; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 293: | Line 293: | ||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">file f; |
||
text s; |
text s; |
||
Line 301: | Line 301: | ||
o_text(s); |
o_text(s); |
||
o_byte('\n'); |
o_byte('\n'); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 307: | 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].}} |
{{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''.}} |
{{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: ./Read_a_file_line_by_line.a68'''<syntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script # |
||
FILE foobar; |
FILE foobar; |
||
Line 327: | Line 327: | ||
printf(($g(0)": "$, count, line fmt, line)) |
printf(($g(0)": "$, count, line fmt, line)) |
||
OD; |
OD; |
||
done: SKIP</ |
done: SKIP</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre style="height:15ex;overflow:scroll"> |
<pre style="height:15ex;overflow:scroll"> |
||
Line 354: | Line 354: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
<syntaxhighlight lang="apl"> |
|||
<lang APL> |
|||
⍝⍝ GNU APL Version |
⍝⍝ GNU APL Version |
||
∇listFile fname ;fileHandle;maxLineLen;line |
∇listFile fname ;fileHandle;maxLineLen;line |
||
Line 376: | Line 376: | ||
This is the end of the text. |
This is the end of the text. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Amazing Hopper}}== |
=={{header|Amazing Hopper}}== |
||
<syntaxhighlight lang="amazing hopper"> |
|||
<lang Amazing Hopper> |
|||
#include <hopper.h> |
#include <hopper.h> |
||
Line 399: | Line 399: | ||
println |
println |
||
exit(0) |
exit(0) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 413: | Line 413: | ||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |
||
<syntaxhighlight lang="arm assembly"> |
|||
<lang ARM Assembly> |
|||
/* ARM assembly Raspberry PI */ |
/* ARM assembly Raspberry PI */ |
||
/* program readfile.s */ |
/* program readfile.s */ |
||
Line 698: | Line 698: | ||
iMagicNumber: .int 0xCCCCCCCD |
iMagicNumber: .int 0xCCCCCCCD |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Astro}}== |
=={{header|Astro}}== |
||
< |
<syntaxhighlight lang="python">for line in lines open('input.txt'): |
||
print line |
print line |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">; --> Prompt the user to select the file being read |
||
FileSelectFile, File, 1, %A_ScriptDir%, Select the (text) file to read, Documents (*.txt) ; Could of course be set to support other filetypes |
FileSelectFile, File, 1, %A_ScriptDir%, Select the (text) file to read, Documents (*.txt) ; Could of course be set to support other filetypes |
||
Line 727: | Line 727: | ||
FileDelete, Output.txt ; Makes sure output is clear before writing |
FileDelete, Output.txt ; Makes sure output is clear before writing |
||
FileAppend, %Text%, Output.txt ; Writes the result to Output.txt |
FileAppend, %Text%, Output.txt ; Writes the result to Output.txt |
||
Run Output.txt ; Shows the created file</ |
Run Output.txt ; Shows the created file</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
Line 733: | Line 733: | ||
'''One-liner:''' |
'''One-liner:''' |
||
< |
<syntaxhighlight lang="awk">awk '{ print $0 }' filename</syntaxhighlight> |
||
'''Shorter:'''<br> |
'''Shorter:'''<br> |
||
Line 740: | Line 740: | ||
so this is the shortest possible awk-program |
so this is the shortest possible awk-program |
||
(not counting the [[Empty program]]): |
(not counting the [[Empty program]]): |
||
< |
<syntaxhighlight lang="awk">awk '1' filename</syntaxhighlight> |
||
'''Longer:'''<br> |
'''Longer:'''<br> |
||
Reading several files, with some processing: |
Reading several files, with some processing: |
||
< |
<syntaxhighlight lang="awk"># usage: awk -f readlines.awk *.txt |
||
BEGIN { print "# Reading..." } |
BEGIN { print "# Reading..." } |
||
FNR==1 { f++; print "# File #" f, ":", FILENAME } |
FNR==1 { f++; print "# File #" f, ":", FILENAME } |
||
Line 752: | Line 752: | ||
{ print } # same as "print $0" |
{ print } # same as "print $0" |
||
END { print "# Done with", f, "file(s), with a total of", NR, "lines." } |
END { print "# Done with", f, "file(s), with a total of", NR, "lines." } |
||
END { print "# Comment-lines:", c }</ |
END { print "# Comment-lines:", c }</syntaxhighlight> |
||
Note: |
Note: |
||
* The variables c and f are initialized automatically to 0 |
* The variables c and f are initialized automatically to 0 |
||
Line 781: | Line 781: | ||
==={{header|BaCon}}=== |
==={{header|BaCon}}=== |
||
< |
<syntaxhighlight lang="freebasic">' Read a file line by line |
||
filename$ = "readlines.bac" |
filename$ = "readlines.bac" |
||
OPEN filename$ FOR READING AS fh |
OPEN filename$ FOR READING AS fh |
||
Line 790: | Line 790: | ||
WEND |
WEND |
||
PRINT lines, " lines in ", filename$ |
PRINT lines, " lines in ", filename$ |
||
CLOSE FILE fh</ |
CLOSE FILE fh</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 797: | Line 797: | ||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
< |
<syntaxhighlight lang="is-basic">100 INPUT PROMPT "Filename: ":NAME$ |
||
110 OPEN #1:NAME$ ACCESS INPUT |
110 OPEN #1:NAME$ ACCESS INPUT |
||
120 COPY FROM #1 TO #0 |
120 COPY FROM #1 TO #0 |
||
130 CLOSE #1</ |
130 CLOSE #1</syntaxhighlight> |
||
==={{header|Locomotive Basic}}=== |
==={{header|Locomotive Basic}}=== |
||
< |
<syntaxhighlight lang="locobasic">10 OPENIN"foo.txt" |
||
20 WHILE NOT EOF |
20 WHILE NOT EOF |
||
30 LINE INPUT#9,i$ |
30 LINE INPUT#9,i$ |
||
40 PRINT i$ |
40 PRINT i$ |
||
50 WEND</ |
50 WEND</syntaxhighlight> |
||
==={{header|OxygenBasic}}=== |
==={{header|OxygenBasic}}=== |
||
The core function '''GetFile''' reads the whole file: |
The core function '''GetFile''' reads the whole file: |
||
< |
<syntaxhighlight lang="oxygenbasic"> |
||
function getline(string s, int *i) as string |
function getline(string s, int *i) as string |
||
int sl=i, el=i |
int sl=i, el=i |
||
Line 848: | Line 848: | ||
done: |
done: |
||
print "Line count " c |
print "Line count " c |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|QBasic}}=== |
==={{header|QBasic}}=== |
||
{{works with|QBasic}} |
{{works with|QBasic}} |
||
{{works with|QuickBasic}} |
{{works with|QuickBasic}} |
||
< |
<syntaxhighlight lang="qbasic">f = FREEFILE |
||
filename$ = "file.txt" |
filename$ = "file.txt" |
||
Line 863: | Line 863: | ||
WEND |
WEND |
||
CLOSE #f |
CLOSE #f |
||
END</ |
END</syntaxhighlight> |
||
==={{header|uBasic/4tH}}=== |
==={{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. |
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. |
||
<lang>If Set (a, Open ("myfile.bas", "r")) < 0 Then Print "Cannot open \qmyfile.bas\q" : End |
<syntaxhighlight lang="text">If Set (a, Open ("myfile.bas", "r")) < 0 Then Print "Cannot open \qmyfile.bas\q" : End |
||
Do While Read (a) |
Do While Read (a) |
||
Line 874: | Line 874: | ||
Close a |
Close a |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|ZX Spectrum Basic}}=== |
==={{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). |
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: | Line 880: | ||
In the following example, we read a file line by line from a file on microdrive 1. |
In the following example, we read a file line by line from a file on microdrive 1. |
||
< |
<syntaxhighlight lang="basic">10 REM open my file for input |
||
20 OPEN #4;"m";1;"MYFILE": REM stream 4 is the first available for general purpose |
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 |
30 INPUT #4; LINE a$: REM a$ will hold our line from the file |
||
Line 886: | Line 886: | ||
50 REM to gracefully exit when the file is read. (omitted from this example) |
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 |
60 REM to prevent an error at end of file, place a handler here |
||
100 GOTO 30</ |
100 GOTO 30</syntaxhighlight> |
||
=={{header|BASIC256}}== |
=={{header|BASIC256}}== |
||
< |
<syntaxhighlight lang="basic256">f = freefile |
||
filename$ = "file.txt" |
filename$ = "file.txt" |
||
Line 898: | Line 898: | ||
end while |
end while |
||
close f |
close f |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
This takes account on the blank lines, because FOR ignores blank lines when reading a file. |
This takes account on the blank lines, because FOR ignores blank lines when reading a file. |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
rem delayed expansion must be disabled before the FOR command. |
rem delayed expansion must be disabled before the FOR command. |
||
setlocal disabledelayedexpansion |
setlocal disabledelayedexpansion |
||
Line 911: | Line 911: | ||
echo(!var! |
echo(!var! |
||
endlocal |
endlocal |
||
)</ |
)</syntaxhighlight> |
||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
This method is appropriate if the lines are terminated by a single CR or LF: |
This method is appropriate if the lines are terminated by a single CR or LF: |
||
< |
<syntaxhighlight lang="bbcbasic"> file% = OPENIN("*.txt") |
||
IF file%=0 ERROR 100, "File could not be opened" |
IF file%=0 ERROR 100, "File could not be opened" |
||
WHILE NOT EOF#file% |
WHILE NOT EOF#file% |
||
a$ = GET$#file% |
a$ = GET$#file% |
||
ENDWHILE |
ENDWHILE |
||
CLOSE #file%</ |
CLOSE #file%</syntaxhighlight> |
||
This method is appropriate if the lines are terminated by a CRLF pair: |
This method is appropriate if the lines are terminated by a CRLF pair: |
||
< |
<syntaxhighlight lang="bbcbasic"> file% = OPENIN("*.txt") |
||
IF file%=0 ERROR 100, "File could not be opened" |
IF file%=0 ERROR 100, "File could not be opened" |
||
WHILE NOT EOF#file% |
WHILE NOT EOF#file% |
||
Line 929: | Line 929: | ||
IF ASCa$=10 a$ = MID$(a$,2) |
IF ASCa$=10 a$ = MID$(a$,2) |
||
ENDWHILE |
ENDWHILE |
||
CLOSE #file%</ |
CLOSE #file%</syntaxhighlight> |
||
=={{header|Bracmat}}== |
=={{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. |
<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. |
||
< |
<syntaxhighlight lang="bracmat"> fil$("test.txt",r) { r opens a text file, rb opens a binary file for reading } |
||
& fil$(,STR,\n) { first argument empty: same as before (i.e. "test.txt") } |
& 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 } |
{ if \n were replaced by e.g. "\n\t " we would read word-wise instead } |
||
Line 942: | Line 942: | ||
) |
) |
||
& (fil$(,SET,-1)|); { Setting file position before start closes file, and fails. |
& (fil$(,SET,-1)|); { Setting file position before start closes file, and fails. |
||
Therefore the | }</ |
Therefore the | }</syntaxhighlight> |
||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang="brat">include :file |
||
file.each_line "foobar.txt" { line | |
file.each_line "foobar.txt" { line | |
||
p line |
p line |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">/* Programa: Número mayor de tres números introducidos (Solución 1) */ |
||
#include <conio.h> |
#include <conio.h> |
||
Line 980: | Line 980: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
===with getline=== |
===with getline=== |
||
< |
<syntaxhighlight lang="c">// From manpage for "getline" |
||
#include <stdio.h> |
#include <stdio.h> |
||
Line 1,007: | Line 1,007: | ||
fclose(stream); |
fclose(stream); |
||
exit(EXIT_SUCCESS); |
exit(EXIT_SUCCESS); |
||
}</ |
}</syntaxhighlight> |
||
=== Using mmap() === |
=== 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. |
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. |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <sys/types.h> |
#include <sys/types.h> |
||
#include <sys/stat.h> |
#include <sys/stat.h> |
||
Line 1,086: | Line 1,086: | ||
return read_lines("test.ps", print_line) ? 0 : 1; |
return read_lines("test.ps", print_line) ? 0 : 1; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
'File.ReadLines' reads the lines of a file which could easily be stepped through. |
'File.ReadLines' reads the lines of a file which could easily be stepped through. |
||
< |
<syntaxhighlight lang="csharp">foreach (string readLine in File.ReadLines("FileName")) |
||
DoSomething(readLine);</ |
DoSomething(readLine);</syntaxhighlight> |
||
A full code may look like; |
A full code may look like; |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.IO; |
using System.IO; |
||
using System.Text; |
using System.Text; |
||
Line 1,126: | Line 1,126: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{works with|C++03 to C++17 }} |
{{works with|C++03 to C++17 }} |
||
< |
<syntaxhighlight lang="cpp">#include <fstream> |
||
#include <string> |
#include <string> |
||
#include <iostream> |
#include <iostream> |
||
Line 1,147: | Line 1,147: | ||
infile.close( ) ; |
infile.close( ) ; |
||
return 0 ; |
return 0 ; |
||
}</ |
}</syntaxhighlight> |
||
====using std::getline==== |
====using std::getline==== |
||
Line 1,160: | Line 1,160: | ||
</pre> |
</pre> |
||
< |
<syntaxhighlight lang="cpp"> |
||
#include <fstream> |
#include <fstream> |
||
#include <iostream> |
#include <iostream> |
||
Line 1,180: | Line 1,180: | ||
} |
} |
||
std::cout << "finished" << std::endl; |
std::cout << "finished" << std::endl; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,195: | Line 1,195: | ||
{{libheader|U++}} |
{{libheader|U++}} |
||
< |
<syntaxhighlight lang="cpp">#include <Core/Core.h> |
||
using namespace Upp; |
using namespace Upp; |
||
Line 1,204: | Line 1,204: | ||
while(in && !in.IsEof()) |
while(in && !in.IsEof()) |
||
Cout().PutLine(in.GetLine()); |
Cout().PutLine(in.GetLine()); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
<syntaxhighlight lang="clojure"> |
|||
<lang Clojure> |
|||
(with-open [r (clojure.java.io/reader "some-file.txt")] |
(with-open [r (clojure.java.io/reader "some-file.txt")] |
||
(doseq [l (line-seq r)] |
(doseq [l (line-seq r)] |
||
(println l))) |
(println l))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|CLU}}== |
=={{header|CLU}}== |
||
< |
<syntaxhighlight lang="clu">start_up = proc () |
||
po: stream := stream$primary_output() |
po: stream := stream$primary_output() |
||
Line 1,241: | Line 1,241: | ||
stream$close(fstream) |
stream$close(fstream) |
||
end |
end |
||
end start_up</ |
end start_up</syntaxhighlight> |
||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. read-file-line-by-line. |
PROGRAM-ID. read-file-line-by-line. |
||
Line 1,281: | Line 1,281: | ||
GOBACK |
GOBACK |
||
.</ |
.</syntaxhighlight> |
||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
{{works_with|node.js}} |
{{works_with|node.js}} |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
# This module shows two ways to read a file line-by-line in node.js. |
# This module shows two ways to read a file line-by-line in node.js. |
||
fs = require 'fs' |
fs = require 'fs' |
||
Line 1,366: | Line 1,366: | ||
console.log "DONE ASYNC!" |
console.log "DONE ASYNC!" |
||
reader.next_line callbacks.process_line, callbacks.all_done |
reader.next_line callbacks.process_line, callbacks.all_done |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(with-open-file (input "file.txt") |
||
(loop for line = (read-line input nil) |
(loop for line = (read-line input nil) |
||
while line do (format t "~a~%" line)))</ |
while line do (format t "~a~%" line)))</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">void main() { |
||
import std.stdio; |
import std.stdio; |
||
foreach (line; "read_a_file_line_by_line.d".File.byLine) |
foreach (line; "read_a_file_line_by_line.d".File.byLine) |
||
line.writeln; |
line.writeln; |
||
}</ |
}</syntaxhighlight> |
||
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. |
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}}== |
=={{header|DBL}}== |
||
<syntaxhighlight lang="dbl">; |
|||
<lang DBL>; |
|||
; Read a file line by line for DBL version 4 |
; Read a file line by line for DBL version 4 |
||
; |
; |
||
Line 1,408: | Line 1,408: | ||
GOTO CLOS |
GOTO CLOS |
||
CLOS, STOP</ |
CLOS, STOP</syntaxhighlight> |
||
=={{header|DCL}}== |
=={{header|DCL}}== |
||
< |
<syntaxhighlight lang="dcl">$ open input input.txt |
||
$ loop: |
$ loop: |
||
$ read /end_of_file = done input line |
$ read /end_of_file = done input line |
||
$ goto loop |
$ goto loop |
||
$ done: |
$ done: |
||
$ close input</ |
$ close input</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
procedure ReadFileByLine; |
procedure ReadFileByLine; |
||
var |
var |
||
Line 1,431: | Line 1,431: | ||
CloseFile(TextFile); |
CloseFile(TextFile); |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
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"'''. |
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"> |
|||
<lang Delphi> |
|||
procedure ReadFileByLine; |
procedure ReadFileByLine; |
||
var |
var |
||
Line 1,445: | Line 1,445: | ||
ShowMessage(TextLines[i]); |
ShowMessage(TextLines[i]); |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Above uses the powerful utility classs type [http://www.delphibasics.co.uk/RTL.asp?Name=TStringList TStringList] from Classes Unit |
Above uses the powerful utility classs type [http://www.delphibasics.co.uk/RTL.asp?Name=TStringList TStringList] from Classes Unit |
||
Line 1,452: | Line 1,452: | ||
=={{header|Draco}}== |
=={{header|Draco}}== |
||
< |
<syntaxhighlight lang="draco">\util.g |
||
proc nonrec main() void: |
proc nonrec main() void: |
||
/* first we need to declare a file buffer and an input channel */ |
/* first we need to declare a file buffer and an input channel */ |
||
Line 1,480: | Line 1,480: | ||
/* finally, close the file */ |
/* finally, close the file */ |
||
close(in_ch) |
close(in_ch) |
||
corp</ |
corp</syntaxhighlight> |
||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 4.x : |
ELENA 4.x : |
||
< |
<syntaxhighlight lang="elena">import system'io; |
||
import extensions; |
import extensions; |
||
import extensions'routines; |
import extensions'routines; |
||
Line 1,491: | Line 1,491: | ||
{ |
{ |
||
File.assign:"file.txt".forEachLine(printingLn) |
File.assign:"file.txt".forEachLine(printingLn) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
Two Slightly different solutions in the FileReader namespace |
Two Slightly different solutions in the FileReader namespace |
||
<syntaxhighlight lang="elixir"> |
|||
<lang Elixir> |
|||
defmodule FileReader do |
defmodule FileReader do |
||
# Create a File.Stream and inspect each line |
# Create a File.Stream and inspect each line |
||
Line 1,519: | Line 1,519: | ||
end |
end |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Erlang}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="erlang"> |
||
-module( read_a_file_line_by_line ). |
-module( read_a_file_line_by_line ). |
||
Line 1,536: | Line 1,536: | ||
into_list( {error, _Error}, _IO, Acc ) -> lists:reverse( Acc ); |
into_list( {error, _Error}, _IO, Acc ) -> lists:reverse( Acc ); |
||
into_list( Line, IO, Acc ) -> into_list( io:get_line(IO, ''), IO, [Line | Acc] ). |
into_list( Line, IO, Acc ) -> into_list( io:get_line(IO, ''), IO, [Line | Acc] ). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,551: | Line 1,551: | ||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
PROGRAM LETTURA |
PROGRAM LETTURA |
||
Line 1,573: | Line 1,573: | ||
CLOSE(1) ! chiude il file |
CLOSE(1) ! chiude il file |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
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. |
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}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">constant cmd = command_line() |
||
constant filename = cmd[2] |
constant filename = cmd[2] |
||
constant fn = open(filename,"r") |
constant fn = open(filename,"r") |
||
Line 1,591: | Line 1,591: | ||
i += 1 |
i += 1 |
||
end while |
end while |
||
close(fn)</ |
close(fn)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,625: | 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. |
(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. |
||
< |
<syntaxhighlight lang="euphoria">constant cmd = command_line() |
||
constant filename = cmd[3] |
constant filename = cmd[3] |
||
constant fn = open(filename,"r") |
constant fn = open(filename,"r") |
||
Line 1,639: | Line 1,639: | ||
i += 1 |
i += 1 |
||
end while |
end while |
||
close(fn)</ |
close(fn)</syntaxhighlight> |
||
From the command line run: |
From the command line run: |
||
< |
<syntaxhighlight lang="cmd"> |
||
eui readfile.ex "File.txt" |
eui readfile.ex "File.txt" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,660: | Line 1,660: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
Using DotNet's [http://msdn.microsoft.com/en-us/library/dd383503.aspx System.IO.File.ReadLines] iterator: |
Using DotNet's [http://msdn.microsoft.com/en-us/library/dd383503.aspx System.IO.File.ReadLines] iterator: |
||
< |
<syntaxhighlight lang="fsharp">open System.IO |
||
[<EntryPoint>] |
[<EntryPoint>] |
||
let main argv = |
let main argv = |
||
File.ReadLines(argv.[0]) |> Seq.iter (printfn "%s") |
File.ReadLines(argv.[0]) |> Seq.iter (printfn "%s") |
||
0</ |
0</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor"> "path/to/file" utf8 [ [ readln dup [ print ] when* ] loop ] with-file-reader</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
Line 1,675: | Line 1,675: | ||
Reads each line from the file "data.txt". |
Reads each line from the file "data.txt". |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 1,686: | Line 1,686: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">4096 constant max-line |
||
: third ( A b c -- A b c A ) |
: third ( A b c -- A b c A ) |
||
Line 1,699: | Line 1,699: | ||
while pad swap ( fileid c-addr u ) \ string excludes the newline |
while pad swap ( fileid c-addr u ) \ string excludes the newline |
||
2drop |
2drop |
||
repeat 2drop ;</ |
repeat 2drop ;</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
Line 1,714: | 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. |
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"> |
|||
<lang Fortran> |
|||
INTEGER ENUFF !A value has to be specified beforehand,. |
INTEGER ENUFF !A value has to be specified beforehand,. |
||
PARAMETER (ENUFF = 2468) !Provide some provenance. |
PARAMETER (ENUFF = 2468) !Provide some provenance. |
||
Line 1,745: | Line 1,745: | ||
20 CLOSE (IN) !All done. |
20 CLOSE (IN) !All done. |
||
END !That's all. |
END !That's all. |
||
</syntaxhighlight> |
|||
</lang> |
|||
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. |
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: | Line 1,751: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Open "input.txt" For Input As #1 |
Open "input.txt" For Input As #1 |
||
Line 1,762: | Line 1,762: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep </ |
Sleep </syntaxhighlight> |
||
=={{header|Frink}}== |
=={{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>. |
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>. |
||
< |
<syntaxhighlight lang="frink"> |
||
for line = lines["file:yourfile.txt"] |
for line = lines["file:yourfile.txt"] |
||
println[line] |
println[line] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
< |
<syntaxhighlight lang="gambas">Public Sub Main() |
||
Dim hFile As File |
Dim hFile As File |
||
Dim sLine As String |
Dim sLine As String |
||
Line 1,783: | Line 1,783: | ||
Wend |
Wend |
||
End</ |
End</syntaxhighlight> |
||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">ReadByLines := function(name) |
||
local file, line, count; |
local file, line, count; |
||
file := InputTextFile(name); |
file := InputTextFile(name); |
||
Line 1,803: | Line 1,803: | ||
# With [http://www.ibiblio.org/pub/docs/misc/amnesty.txt amnesty.txt] |
# With [http://www.ibiblio.org/pub/docs/misc/amnesty.txt amnesty.txt] |
||
ReadByLines("amnesty.txt"); |
ReadByLines("amnesty.txt"); |
||
# 384</ |
# 384</syntaxhighlight> |
||
=={{header|Genie}}== |
=={{header|Genie}}== |
||
< |
<syntaxhighlight lang="genie">[indent=4] |
||
/* |
/* |
||
Read file line by line, in Genie |
Read file line by line, in Genie |
||
Line 1,828: | Line 1,828: | ||
lines++ |
lines++ |
||
stdout.printf("%04d %s\n", lines, line) |
stdout.printf("%04d %s\n", lines, line) |
||
line = file.read_line()</ |
line = file.read_line()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,846: | 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. |
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. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,884: | Line 1,884: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
;ReadLine |
;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. |
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. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,950: | Line 1,950: | ||
fmt.Println(string(line)) |
fmt.Println(string(line)) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
;ReadString |
;ReadString |
||
In comparison, ReadString is a little quick and dirty, but is often good enough. |
In comparison, ReadString is a little quick and dirty, but is often good enough. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,984: | Line 1,984: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
< |
<syntaxhighlight lang="groovy">new File("Test.txt").eachLine { line, lineNumber -> |
||
println "processing line $lineNumber: $line" |
println "processing line $lineNumber: $line" |
||
}</ |
}</syntaxhighlight> |
||
Line 1,995: | Line 1,995: | ||
Thanks to laziness, there's no difference between reading the file all at once and reading it line by line. |
Thanks to laziness, there's no difference between reading the file all at once and reading it line by line. |
||
< |
<syntaxhighlight lang="haskell">main = do |
||
file <- readFile "linebyline.hs" |
file <- readFile "linebyline.hs" |
||
mapM_ putStrLn (lines file) |
mapM_ putStrLn (lines file) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{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. |
Line oriented I/O is basic. This program reads lines from "input.txt" into the variable line, but does nothing with it. |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
f := open("input.txt","r") | stop("cannot open file ",fn) |
f := open("input.txt","r") | stop("cannot open file ",fn) |
||
while line := read(f) |
while line := read(f) |
||
close(f) |
close(f) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 2,017: | 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. |
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. |
||
< |
<syntaxhighlight lang="j">cocurrent 'linereader' |
||
NB. configuration parameter |
NB. configuration parameter |
||
Line 2,050: | Line 2,050: | ||
lines=: }.lines |
lines=: }.lines |
||
r |
r |
||
)</ |
)</syntaxhighlight> |
||
< |
<syntaxhighlight lang="j"> example=: '/tmp/example.txt' conew 'linereader' |
||
next__example'' |
next__example'' |
||
this is line 1 |
this is line 1 |
||
next__example'' |
next__example'' |
||
and this is line 2</ |
and this is line 2</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">import java.io.BufferedReader; |
||
import java.io.FileReader; |
import java.io.FileReader; |
||
Line 2,097: | Line 2,097: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{works with|Java|7+}} |
{{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: |
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: |
||
< |
<syntaxhighlight lang="java5">for (String filename : args) { |
||
try (FileReader fr = new FileReader(filename);BufferedReader br = new BufferedReader(fr)){ |
try (FileReader fr = new FileReader(filename);BufferedReader br = new BufferedReader(fr)){ |
||
String line; |
String line; |
||
Line 2,111: | Line 2,111: | ||
x.printStackTrace(); |
x.printStackTrace(); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
<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). |
<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>): |
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>): |
||
< |
<syntaxhighlight lang="java5">import java.nio.file.Files; |
||
import java.nio.file.Paths; |
import java.nio.file.Paths; |
||
import java.nio.charset.Charset; |
import java.nio.charset.Charset; |
||
Line 2,125: | Line 2,125: | ||
}catch(IOException | SecurityException e){ |
}catch(IOException | SecurityException e){ |
||
//problem with the file |
//problem with the file |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang="javascript">var fs = require("fs"); |
||
var readFile = function(path) { |
var readFile = function(path) { |
||
Line 2,134: | Line 2,134: | ||
}; |
}; |
||
console.log(readFile('file.txt'));</ |
console.log(readFile('file.txt'));</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
When invoked with the -R option, jq will read each line as a JSON string. For example: |
When invoked with the -R option, jq will read each line as a JSON string. For example: |
||
< |
<syntaxhighlight lang="sh">$ seq 0 5 | jq -R 'tonumber|sin' |
||
0 |
0 |
||
0.8414709848078965 |
0.8414709848078965 |
||
Line 2,144: | Line 2,144: | ||
0.1411200080598672 |
0.1411200080598672 |
||
-0.7568024953079282 |
-0.7568024953079282 |
||
-0.9589242746631385</ |
-0.9589242746631385</syntaxhighlight> |
||
To perform any kind of reduction operation while reading the lines one-by-one, one would normally use |
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: |
`input` or `inputs`. For example, to compute the maximum of the above sin values: |
||
< |
<syntaxhighlight lang="sh">$ seq 0 5 | jq -Rn '[inputs | tonumber |sin] | max' |
||
0.9092974268256817</ |
0.9092974268256817</syntaxhighlight> |
||
=={{header|Jsish}}== |
=={{header|Jsish}}== |
||
< |
<syntaxhighlight lang="javascript">/* Read by line, in Jsish */ |
||
var f = new Channel('read-by-line.jsi'); |
var f = new Channel('read-by-line.jsi'); |
||
var line; |
var line; |
||
while (line = f.gets()) puts(line); |
while (line = f.gets()) puts(line); |
||
f.close();</ |
f.close();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>prompt$ jsish read-by-line.jsi |
<pre>prompt$ jsish read-by-line.jsi |
||
Line 2,169: | Line 2,169: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">open("input_file","r") do f |
||
for line in eachline(f) |
for line in eachline(f) |
||
println("read line: ", line) |
println("read line: ", line) |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.1.2 |
||
import java.io.File |
import java.io.File |
||
Line 2,182: | Line 2,182: | ||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
File("input.txt").forEachLine { println(it) } |
File("input.txt").forEachLine { println(it) } |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">local(f) = file('foo.txt') |
||
handle => {#f->close} |
handle => {#f->close} |
||
#f->forEachLine => {^ |
#f->forEachLine => {^ |
||
#1 |
#1 |
||
'<br>' // note this simply inserts an HTML line break between each line. |
'<br>' // note this simply inserts an HTML line break between each line. |
||
^}</ |
^}</syntaxhighlight> |
||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb">filedialog "Open","*.txt",file$ |
||
if file$="" then end |
if file$="" then end |
||
open file$ for input as #f |
open file$ for input as #f |
||
Line 2,200: | Line 2,200: | ||
print t$ |
print t$ |
||
wend |
wend |
||
close #f</ |
close #f</syntaxhighlight> |
||
Mac |
Mac |
||
< |
<syntaxhighlight lang="lb">filedialog "Open","*.txt",file$ |
||
if file$="" then end |
if file$="" then end |
||
open file$ for input as #f |
open file$ for input as #f |
||
Line 2,209: | Line 2,209: | ||
print t$ |
print t$ |
||
wend |
wend |
||
close #f </ |
close #f </syntaxhighlight> |
||
Unix |
Unix |
||
< |
<syntaxhighlight lang="lb">filedialog "Open","*.txt",file$ |
||
if file$="" then end |
if file$="" then end |
||
open file$ for input as #f |
open file$ for input as #f |
||
Line 2,218: | Line 2,218: | ||
print t$ |
print t$ |
||
wend |
wend |
||
close #f </ |
close #f </syntaxhighlight> |
||
=={{header|Lingo}}== |
=={{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): |
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): |
||
< |
<syntaxhighlight lang="lingo">fp = xtra("fileIO").new() |
||
fp.openFile(_movie.path & "input.txt", 1) |
fp.openFile(_movie.path & "input.txt", 1) |
||
fileSize = fp.getLength() |
fileSize = fp.getLength() |
||
Line 2,232: | Line 2,232: | ||
if fp.getPosition()>=fileSize then exit repeat |
if fp.getPosition()>=fileSize then exit repeat |
||
end repeat |
end repeat |
||
fp.closeFile()</ |
fp.closeFile()</syntaxhighlight> |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang="livecode">command readFileLineByLine |
||
local tFile, tLines, startRead |
local tFile, tLines, startRead |
||
put "/usr/share/dict/words" into tFile |
put "/usr/share/dict/words" into tFile |
||
Line 2,247: | Line 2,247: | ||
close file tFile |
close file tFile |
||
put tLines |
put tLines |
||
end readFileLineByLine</ |
end readFileLineByLine</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
Line 2,254: | Line 2,254: | ||
* readword - returns a line as a single word, or an empty list if it reached the end of file |
* readword - returns a line as a single word, or an empty list if it reached the end of file |
||
* readrawline - returns a line as a single word, with no characters escaped |
* readrawline - returns a line as a single word, with no characters escaped |
||
< |
<syntaxhighlight lang="logo">while [not eof?] [print readline]</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">filename = "input.txt" |
||
fp = io.open( filename, "r" ) |
fp = io.open( filename, "r" ) |
||
Line 2,265: | Line 2,265: | ||
fp:close() |
fp:close() |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Simpler version=== |
===Simpler version=== |
||
The following achieves the same result as the example above, including implicitly closing the file at the end of the loop. |
The following achieves the same result as the example above, including implicitly closing the file at the end of the loop. |
||
<syntaxhighlight lang="lua"> |
|||
<lang Lua> |
|||
for line in io.lines("input.txt") do |
for line in io.lines("input.txt") do |
||
print(line) |
print(line) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
Line 2,278: | 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. |
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"> |
|||
<lang M2000 Interpreter> |
|||
Module checkit { |
Module checkit { |
||
\\ prepare a file |
\\ prepare a file |
||
Line 2,332: | Line 2,332: | ||
} |
} |
||
checkit |
checkit |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang="maple">path := "file.txt": |
||
while (true) do |
while (true) do |
||
input := readline(path): |
input := readline(path): |
||
if input = 0 then break; end if: |
if input = 0 then break; end if: |
||
#The line is stored in input |
#The line is stored in input |
||
end do:</ |
end do:</syntaxhighlight> |
||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">strm=OpenRead["input.txt"]; |
||
If[strm=!=$Failed, |
If[strm=!=$Failed, |
||
While[line=!=EndOfFile, |
While[line=!=EndOfFile, |
||
Line 2,349: | Line 2,349: | ||
(*Do something*) |
(*Do something*) |
||
]]; |
]]; |
||
Close[strm];</ |
Close[strm];</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
Line 2,355: | Line 2,355: | ||
The function fgetl() read lines from file: |
The function fgetl() read lines from file: |
||
<syntaxhighlight lang="matlab"> |
|||
<lang Matlab> |
|||
fid = fopen('foobar.txt','r'); |
fid = fopen('foobar.txt','r'); |
||
if (fid < 0) |
if (fid < 0) |
||
Line 2,365: | Line 2,365: | ||
end; |
end; |
||
fclose(fid) |
fclose(fid) |
||
end; </ |
end; </syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">/* Read a file and return a list of all lines */ |
||
readfile(name) := block( |
readfile(name) := block( |
||
Line 2,375: | Line 2,375: | ||
close(f), |
close(f), |
||
v |
v |
||
)$</ |
)$</syntaxhighlight> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
Basic version. |
Basic version. |
||
< |
<syntaxhighlight lang="mercury">:- module read_a_file_line_by_line. |
||
:- interface. |
:- interface. |
||
Line 2,417: | Line 2,417: | ||
ReadLineResult = error(Error), |
ReadLineResult = error(Error), |
||
error(io.error_message(Error)) |
error(io.error_message(Error)) |
||
).</ |
).</syntaxhighlight> |
||
Version using a stream fold. |
Version using a stream fold. |
||
< |
<syntaxhighlight lang="mercury">:- module read_a_file_line_by_line. |
||
:- interface. |
:- interface. |
||
Line 2,452: | Line 2,452: | ||
process_line(line(Line), !LineCount, !IO) :- |
process_line(line(Line), !LineCount, !IO) :- |
||
!:LineCount = !.LineCount + 1, |
!:LineCount = !.LineCount + 1, |
||
io.format("%d: %s", [i(!.LineCount), s(Line)], !IO).</ |
io.format("%d: %s", [i(!.LineCount), s(Line)], !IO).</syntaxhighlight> |
||
=={{header|Neko}}== |
=={{header|Neko}}== |
||
Need to define a growing buffer to handle streaming unknown sizes, 2 to the 29 max, for this one. |
Need to define a growing buffer to handle streaming unknown sizes, 2 to the 29 max, for this one. |
||
<syntaxhighlight lang="actionscript">/** |
|||
<lang ActionScript>/** |
|||
Read a file line by line, in Neko |
Read a file line by line, in Neko |
||
<doc><pre>Tectonics: |
<doc><pre>Tectonics: |
||
Line 2,512: | Line 2,512: | ||
} catch a break; |
} catch a break; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 2,533: | Line 2,533: | ||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
=== Using Java <tt>Scanner</tt> === |
=== Using Java <tt>Scanner</tt> === |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref symbols nobinary |
options replace format comments java crossref symbols nobinary |
||
Line 2,564: | Line 2,564: | ||
return fileLines |
return fileLines |
||
</syntaxhighlight> |
|||
</lang> |
|||
=== Using Java <tt>Reader</tt> === |
=== Using Java <tt>Reader</tt> === |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref symbols nobinary |
options replace format comments java crossref symbols nobinary |
||
Line 2,613: | Line 2,613: | ||
return fileLines |
return fileLines |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
<syntaxhighlight lang="newlisp"> |
|||
<lang NewLISP> |
|||
(set 'in-file (open "filename" "read")) |
(set 'in-file (open "filename" "read")) |
||
(while (read-line in-file) |
(while (read-line in-file) |
||
(write-line)) |
(write-line)) |
||
(close in-file)</ |
(close in-file)</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">for line in lines "input.txt": |
||
echo line</ |
echo line</syntaxhighlight> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
bundle Default { |
bundle Default { |
||
class ReadFile { |
class ReadFile { |
||
Line 2,643: | Line 2,643: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
To read an entire file into a string, you can: |
To read an entire file into a string, you can: |
||
< |
<syntaxhighlight lang="objc">NSString *path = [NSString stringWithString:@"/usr/share/dict/words"]; |
||
NSError *error = nil; |
NSError *error = nil; |
||
NSString *words = [[NSString alloc] initWithContentsOfFile:path |
NSString *words = [[NSString alloc] initWithContentsOfFile:path |
||
encoding:NSUTF8StringEncoding error:&error]; |
encoding:NSUTF8StringEncoding error:&error]; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Use the UTF-8 encoder on ASCII. |
Use the UTF-8 encoder on ASCII. |
||
Line 2,658: | Line 2,658: | ||
Now to get the individual lines, break down the string: |
Now to get the individual lines, break down the string: |
||
< |
<syntaxhighlight lang="objc">NSArray* lines = [words componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let () = |
||
let ic = open_in "input.txt" in |
let ic = open_in "input.txt" in |
||
try |
try |
||
Line 2,670: | Line 2,670: | ||
done |
done |
||
with End_of_file -> |
with End_of_file -> |
||
close_in ic</ |
close_in ic</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="ocaml">let input_line_opt ic = |
||
try Some (input_line ic) |
try Some (input_line ic) |
||
with End_of_file -> None |
with End_of_file -> None |
||
Line 2,690: | Line 2,690: | ||
let lines = read_lines ic in |
let lines = read_lines ic in |
||
close_in ic; |
close_in ic; |
||
(lines)</ |
(lines)</syntaxhighlight> |
||
we use it like this: |
we use it like this: |
||
< |
<syntaxhighlight lang="ocaml">let () = |
||
let lines = lines_of_file "unixdict.txt" in |
let lines = lines_of_file "unixdict.txt" in |
||
List.iter print_endline lines</ |
List.iter print_endline lines</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">: readFile(fileName) |
||
| line | File new(fileName) forEach: line [ line println ] ;</ |
| line | File new(fileName) forEach: line [ line println ] ;</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Line 2,707: | 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: |
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: |
||
< |
<syntaxhighlight lang="c">FILE *f = fopen(name, "r"); |
||
if (!f) { |
if (!f) { |
||
pari_err(openfiler, "input", name); |
pari_err(openfiler, "input", name); |
||
Line 2,713: | Line 2,713: | ||
while(fgets(line, MAX_LINELEN, f) != NULL) { |
while(fgets(line, MAX_LINELEN, f) != NULL) { |
||
// ... |
// ... |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
{{Works with|Free 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. |
Works for text files. "testin.txt" must exist in directory of program and you must have read/write access. No IO-Checks. |
||
< |
<syntaxhighlight lang="pascal">(* Read a text-file line by line *) |
||
program ReadFileByLine; |
program ReadFileByLine; |
||
var |
var |
||
Line 2,736: | Line 2,736: | ||
Close(InputFile); |
Close(InputFile); |
||
Close(OutputFile) |
Close(OutputFile) |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
For the simple case of iterating over the lines of a file you can do: |
For the simple case of iterating over the lines of a file you can do: |
||
< |
<syntaxhighlight lang="perl">open(my $fh, '<', 'foobar.txt') |
||
|| die "Could not open file: $!"; |
|| die "Could not open file: $!"; |
||
while (<$fh>) |
while (<$fh>) |
||
Line 2,748: | Line 2,748: | ||
process($_); |
process($_); |
||
} |
} |
||
close $fh;</ |
close $fh;</syntaxhighlight> |
||
File encoding can be specified like: |
File encoding can be specified like: |
||
< |
<syntaxhighlight lang="perl">open(my $fh, '< :encoding(UTF-8)', 'foobar.txt') |
||
|| die "Could not open file: $!";</ |
|| die "Could not open file: $!";</syntaxhighlight> |
||
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.) |
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: |
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: |
||
< |
<syntaxhighlight lang="perl">open(my $fh, '<', 'foobar.txt') |
||
|| die "Could not open file: $!"; |
|| die "Could not open file: $!"; |
||
while (my $line = <$fh>) |
while (my $line = <$fh>) |
||
Line 2,762: | Line 2,762: | ||
process($line); |
process($line); |
||
} |
} |
||
close $fh;</ |
close $fh;</syntaxhighlight> |
||
The special use of the angle bracket operator with nothing inside, will read from all files whose names were specified on the command line: |
The special use of the angle bracket operator with nothing inside, will read from all files whose names were specified on the command line: |
||
< |
<syntaxhighlight lang="perl">while (<>) { |
||
chomp; |
chomp; |
||
process($_); |
process($_); |
||
}</ |
}</syntaxhighlight> |
||
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 |
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 |
||
< |
<syntaxhighlight lang="shell">perl myscript.pl 'rm -rf / |'</syntaxhighlight> |
||
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.) |
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: | Line 2,779: | ||
The readline function can be used instead of < >: |
The readline function can be used instead of < >: |
||
< |
<syntaxhighlight lang="perl">open(my $fh, '<', 'foobar.txt') or die "$!"; |
||
while (readline $fh) |
while (readline $fh) |
||
{ ... } |
{ ... } |
||
Line 2,785: | Line 2,785: | ||
while (my $line = readline $fh) |
while (my $line = readline $fh) |
||
{ ... } |
{ ... } |
||
close $fh;</ |
close $fh;</syntaxhighlight> |
||
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. |
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}}== |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
{{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: #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;">integer</span> <span style="color: #000000;">lno</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span> |
||
Line 2,802: | 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: #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> |
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,819: | Line 2,819: | ||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
< |
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt |
||
argument 1 get "r" fopen var f |
argument 1 get "r" fopen var f |
||
Line 2,826: | Line 2,826: | ||
while |
while |
||
f fgets number? if drop f fclose false else print true endif |
f fgets number? if drop f fclose false else print true endif |
||
endwhile</ |
endwhile</syntaxhighlight> |
||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php"><?php |
||
$file = fopen(__FILE__, 'r'); // read current file |
$file = fopen(__FILE__, 'r'); // read current file |
||
while ($line = fgets($file)) { |
while ($line = fgets($file)) { |
||
$line = rtrim($line); // removes linebreaks and spaces at end |
$line = rtrim($line); // removes linebreaks and spaces at end |
||
echo strrev($line) . "\n"; // reverse line and upload it |
echo strrev($line) . "\n"; // reverse line and upload it |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="php"><?php // HOW TO ECHO FILE LINE BY LINE FROM THE COMMAND LINE: php5-cli |
||
$file = fopen('test.txt', 'r'); // OPEN FILE WITH READ ACCESS |
$file = fopen('test.txt', 'r'); // OPEN FILE WITH READ ACCESS |
||
while (!feof($file)) { |
while (!feof($file)) { |
||
$line = rtrim(fgets($file)); // REMOVE TRAILING WHITESPACE AND GET LINE |
$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 |
if($line != NULL) echo("$line\n"); // IF THE LINE ISN'T NULL, ECHO THE LINE |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
Line 2,847: | Line 2,847: | ||
===read_line/1=== |
===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. |
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"), |
FD = open("unixdict.txt"), |
||
while (not at_end_of_stream(FD)) |
while (not at_end_of_stream(FD)) |
||
Line 2,854: | Line 2,854: | ||
end, |
end, |
||
close(FD), |
close(FD), |
||
nl.</ |
nl.</syntaxhighlight> |
||
===read_file_lines=== |
===read_file_lines=== |
||
For reasonable sized files, <code>read_file_lines/1</code> is usually the way to go. |
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")) |
foreach(Line in read_file_lines("unixdict.txt")) |
||
println(Line) |
println(Line) |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(in "foobar.txt" |
||
(while (line) |
(while (line) |
||
(process @) ) )</ |
(process @) ) )</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli"> |
||
read: procedure options (main); |
read: procedure options (main); |
||
declare line character (500) varying; |
declare line character (500) varying; |
||
Line 2,880: | Line 2,880: | ||
end; |
end; |
||
end read; |
end read; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
< |
<syntaxhighlight lang="powershell">$reader = [System.IO.File]::OpenText($mancorfile) |
||
try { |
try { |
||
do { |
do { |
||
Line 2,893: | Line 2,893: | ||
$reader.Close() |
$reader.Close() |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">FileName$ = OpenFileRequester("","foo.txt","*.txt",0) |
||
If ReadFile(0, FileName$) ; use ReadFile instead of OpenFile to include read-only files |
If ReadFile(0, FileName$) ; use ReadFile instead of OpenFile to include read-only files |
||
Line 2,905: | Line 2,905: | ||
Wend |
Wend |
||
CloseFile(0) |
CloseFile(0) |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
For the simple case of iterating over the lines of a file you can do: |
For the simple case of iterating over the lines of a file you can do: |
||
< |
<syntaxhighlight lang="python">with open("foobar.txt") as f: |
||
for line in f: |
for line in f: |
||
process(line)</ |
process(line)</syntaxhighlight> |
||
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> |
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. |
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'. |
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'. |
||
< |
<syntaxhighlight lang="python">import fileinput |
||
for line in fileinput.input(): |
for line in fileinput.input(): |
||
process(line) |
process(line) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r">conn <- file("notes.txt", "r") |
||
while(length(line <- readLines(conn, 1)) > 0) { |
while(length(line <- readLines(conn, 1)) > 0) { |
||
cat(line, "\n") |
cat(line, "\n") |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket">(define (read-next-line-iter file) |
||
(let ((line (read-line file 'any))) |
(let ((line (read-line file 'any))) |
||
(unless (eof-object? line) |
(unless (eof-object? line) |
||
Line 2,935: | Line 2,935: | ||
(newline) |
(newline) |
||
(read-next-line-iter file)))) |
(read-next-line-iter file)))) |
||
(call-with-input-file "foobar.txt" read-next-line-iter)</ |
(call-with-input-file "foobar.txt" read-next-line-iter)</syntaxhighlight> |
||
< |
<syntaxhighlight lang="racket">(define in (open-input-file file-name)) |
||
(for ([line (in-lines in)]) |
(for ([line (in-lines in)]) |
||
(displayln line)) |
(displayln line)) |
||
(close-input-port in)</ |
(close-input-port in)</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(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. |
The lines method is lazy so the following code does indeed read the file line by line, and not all at once. |
||
<lang |
<syntaxhighlight lang="raku" line>for open('test.txt').lines |
||
{ |
{ |
||
.say |
.say |
||
}</ |
}</syntaxhighlight> |
||
In order to be more explicit about the file being read on line at a time, one can write: |
In order to be more explicit about the file being read on line at a time, one can write: |
||
<lang |
<syntaxhighlight lang="raku" line>my $f = open 'test.txt'; |
||
while my $line = $f.get { |
while my $line = $f.get { |
||
say $line; |
say $line; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|RapidQ}}== |
=={{header|RapidQ}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
$Include "Rapidq.inc" |
$Include "Rapidq.inc" |
||
dim file as qfilestream |
dim file as qfilestream |
||
Line 2,970: | Line 2,970: | ||
input "Press enter to exit: ";a$ |
input "Press enter to exit: ";a$ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 2,978: | 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>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. |
<br><br>The '''lineout''' BIF closes the file (in most REXX interpreters); this is done for general housekeeping. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program reads and displays (with a count) a file, one line at a time. */ |
||
parse arg fID . /*obtain optional argument from the CL.*/ |
parse arg fID . /*obtain optional argument from the CL.*/ |
||
if fID=='' then exit 8 /*Was no fileID specified? Then quit. */ |
if fID=='' then exit 8 /*Was no fileID specified? Then quit. */ |
||
Line 2,990: | Line 2,990: | ||
say /*stick a fork in it, we're all done. */ |
say /*stick a fork in it, we're all done. */ |
||
say center(' file ' fID " has " #-1 ' records.', 79, '═') /*show rec count. */ |
say center(' file ' fID " has " #-1 ' records.', 79, '═') /*show rec count. */ |
||
call lineout fID /*close the input file (most REXXes). */</ |
call lineout fID /*close the input file (most REXXes). */</syntaxhighlight><br><br> |
||
=== deluxe version === |
=== deluxe version === |
||
Line 2,998: | Line 2,998: | ||
<br>It can also just show the last line. |
<br>It can also just show the last line. |
||
<br>If appropriate, the program will show the total number of lines in the file. |
<br>If appropriate, the program will show the total number of lines in the file. |
||
<lang |
<syntaxhighlight lang="rexx"></syntaxhighlight> |
||
{{out|output|text= when using the input of: <tt> 123456.TXT </tt>}} |
{{out|output|text= when using the input of: <tt> 123456.TXT </tt>}} |
||
<pre> |
<pre> |
||
Line 3,077: | Line 3,077: | ||
=== ARexx version === |
=== ARexx version === |
||
< |
<syntaxhighlight lang="rexx">/* Also works with Regina if you state OPTIONS AREXX_BIFS ; OPTIONS AREXX_SEMANTICS */ |
||
filename='file.txt' |
filename='file.txt' |
||
contents='' |
contents='' |
||
Line 3,088: | Line 3,088: | ||
ELSE EXIT 20 |
ELSE EXIT 20 |
||
CALL Close filehandle |
CALL Close filehandle |
||
EXIT 0</ |
EXIT 0</syntaxhighlight> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
fp = fopen("C:\Ring\ReadMe.txt","r") |
fp = fopen("C:\Ring\ReadMe.txt","r") |
||
r = "" |
r = "" |
||
Line 3,100: | Line 3,100: | ||
end |
end |
||
fclose(fp) |
fclose(fp) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">IO.foreach "foobar.txt" do |line| |
||
# Do something with line. |
# Do something with line. |
||
puts line |
puts line |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="ruby"># File inherits from IO, so File.foreach also works. |
||
File.foreach("foobar.txt") {|line| puts line}</ |
File.foreach("foobar.txt") {|line| puts line}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="ruby"># IO.foreach and File.foreach can also read a subprocess. |
||
IO.foreach "| grep afs3 /etc/services" do |line| |
IO.foreach "| grep afs3 /etc/services" do |line| |
||
puts line |
puts line |
||
end</ |
end</syntaxhighlight> |
||
''Caution!'' IO.foreach and File.foreach take a portname. |
''Caution!'' IO.foreach and File.foreach take a portname. |
||
Line 3,121: | Line 3,121: | ||
The block form of File.open automatically closes the file after running the block. |
The block form of File.open automatically closes the file after running the block. |
||
< |
<syntaxhighlight lang="ruby">filename = "|strange-name.txt" |
||
File.open(filename) do |file| |
File.open(filename) do |file| |
||
file.each {|line| puts line} |
file.each {|line| puts line} |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">open DefaultDir$ + "\public\filetest.txt" for input as #f |
||
while not(eof(#f)) |
while not(eof(#f)) |
||
line input #f, a$ |
line input #f, a$ |
||
Line 3,133: | Line 3,133: | ||
wend |
wend |
||
close #f |
close #f |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">use std::io::{BufReader,BufRead}; |
||
use std::fs::File; |
use std::fs::File; |
||
Line 3,144: | Line 3,144: | ||
println!("{}", line.unwrap()); |
println!("{}", line.unwrap()); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,152: | Line 3,152: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">import scala.io._ |
||
Source.fromFile("foobar.txt").getLines.foreach(println)</ |
Source.fromFile("foobar.txt").getLines.foreach(println)</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">; Commented line below should be uncommented to use read-line with Guile |
||
;(use-modules (ice-9 rdelim)) |
;(use-modules (ice-9 rdelim)) |
||
Line 3,162: | Line 3,162: | ||
(do ((line (read-line file) (read-line file))) ((eof-object? line)) |
(do ((line (read-line file) (read-line file))) ((eof-object? line)) |
||
(display line) |
(display line) |
||
(newline))</ |
(newline))</syntaxhighlight> |
||
=={{header|Sed}}== |
=={{header|Sed}}== |
||
Through a .sed file: |
Through a .sed file: |
||
< |
<syntaxhighlight lang="sed">#!/bin/sed -f |
||
p |
p |
||
</syntaxhighlight> |
|||
</lang> |
|||
or through a one-liner in bash: |
or through a one-liner in bash: |
||
< |
<syntaxhighlight lang="bash"> |
||
sed p filename |
sed p filename |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
Line 3,188: | Line 3,188: | ||
writeln("LINE: " <& line); |
writeln("LINE: " <& line); |
||
end while; |
end while; |
||
end func;</ |
end func;</syntaxhighlight> |
||
The function [http://seed7.sourceforge.net/libraries/file.htm#hasNext%28in_file%29 hasNext] |
The function [http://seed7.sourceforge.net/libraries/file.htm#hasNext%28in_file%29 hasNext] |
||
Line 3,195: | Line 3,195: | ||
=={{header|SenseTalk}}== |
=={{header|SenseTalk}}== |
||
The simple way: |
The simple way: |
||
< |
<syntaxhighlight lang="sensetalk">repeat with each line of file "input.txt" |
||
put it |
put it |
||
end repeat |
end repeat |
||
</syntaxhighlight> |
|||
</lang> |
|||
The more traditional way: |
The more traditional way: |
||
< |
<syntaxhighlight lang="sensetalk">put "input.txt" into myFile |
||
open file myFile |
open file myFile |
||
Line 3,210: | Line 3,210: | ||
end repeat |
end repeat |
||
close file myFile</ |
close file myFile</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
''FileHandle.each{}'' is lazy, allowing us to do this: |
''FileHandle.each{}'' is lazy, allowing us to do this: |
||
< |
<syntaxhighlight lang="ruby">File(__FILE__).open_r.each { |line| |
||
print line |
print line |
||
}</ |
}</syntaxhighlight> |
||
Same thing explicitly: |
Same thing explicitly: |
||
< |
<syntaxhighlight lang="ruby">var fh = File(__FILE__).open_r |
||
while (fh.readline(\var line)) { |
while (fh.readline(\var line)) { |
||
print line |
print line |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
{{works with|Pharo}} |
{{works with|Pharo}} |
||
< |
<syntaxhighlight lang="smalltalk"> |
||
(StandardFileStream oldFileNamed: 'test.txt') contents lines do: [ :each | Transcript show: each. ] |
(StandardFileStream oldFileNamed: 'test.txt') contents lines do: [ :each | Transcript show: each. ] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{works with|Smalltalk/X}} |
{{works with|Smalltalk/X}} |
||
< |
<syntaxhighlight lang="smalltalk">'foobar.txt' asFilename readingLinesDo:[:eachLine | eachLine printCR]</syntaxhighlight> |
||
alternatively: |
alternatively: |
||
< |
<syntaxhighlight lang="smalltalk">|s| |
||
s := 'foobar.txt' asFilename readStream. |
s := 'foobar.txt' asFilename readStream. |
||
[ s atEnd ] whileFalse:[ |
[ s atEnd ] whileFalse:[ |
||
s nextLine printCR. |
s nextLine printCR. |
||
]. |
]. |
||
s close</ |
s close</syntaxhighlight> |
||
alternatively: |
alternatively: |
||
< |
<syntaxhighlight lang="smalltalk">'foobar.txt' asFilename contents do:[:eachLine | eachLine printCR].</syntaxhighlight> |
||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
Line 3,251: | Line 3,251: | ||
Accessing the variable fails (does not succeed) when the end of file is reached. |
Accessing the variable fails (does not succeed) when the end of file is reached. |
||
< |
<syntaxhighlight lang="snobol4"> input(.infile,20,"readfrom.txt") :f(end) |
||
rdloop output = infile :s(rdloop) |
rdloop output = infile :s(rdloop) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Sparkling}}== |
=={{header|Sparkling}}== |
||
< |
<syntaxhighlight lang="sparkling">let f = fopen("foo.txt", "r"); |
||
if f != nil { |
if f != nil { |
||
var line; |
var line; |
||
Line 3,264: | Line 3,264: | ||
fclose(f); |
fclose(f); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|SPL}}== |
=={{header|SPL}}== |
||
< |
<syntaxhighlight lang="spl">f = "file.txt" |
||
> !#.eof(f) |
> !#.eof(f) |
||
#.output(#.readline(f)) |
#.output(#.readline(f)) |
||
<</ |
<</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">set f [open "foobar.txt"] |
||
while {[gets $f line] >= 0} { |
while {[gets $f line] >= 0} { |
||
# This loops over every line |
# This loops over every line |
||
puts ">>$line<<" |
puts ">>$line<<" |
||
} |
} |
||
close $f</ |
close $f</syntaxhighlight> |
||
=={{header|TorqueScript}}== |
=={{header|TorqueScript}}== |
||
Line 3,284: | Line 3,284: | ||
Read a file line by line: |
Read a file line by line: |
||
<syntaxhighlight lang="torquescript"> |
|||
<lang TorqueScript> |
|||
//Create a file object |
//Create a file object |
||
Line 3,307: | Line 3,307: | ||
%f.delete(); |
%f.delete(); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Turing}}== |
=={{header|Turing}}== |
||
For a named file: |
For a named file: |
||
< |
<syntaxhighlight lang="turing">var f : int |
||
open : f, "rosetta.txt", get |
open : f, "rosetta.txt", get |
||
loop |
loop |
||
Line 3,319: | Line 3,319: | ||
put line |
put line |
||
end loop |
end loop |
||
close : f</ |
close : f</syntaxhighlight> |
||
For a command line argument file (e.g. program.x rosetta.txt): |
For a command line argument file (e.g. program.x rosetta.txt): |
||
< |
<syntaxhighlight lang="turing">loop |
||
exit when eof (1) |
exit when eof (1) |
||
var line: string |
var line: string |
||
get : 1, line:* |
get : 1, line:* |
||
put line |
put line |
||
end loop</ |
end loop</syntaxhighlight> |
||
For standard input (e.g., program.x < rosetta.txt): |
For standard input (e.g., program.x < rosetta.txt): |
||
< |
<syntaxhighlight lang="turing">loop |
||
exit when eof |
exit when eof |
||
var line : string |
var line : string |
||
get line:* |
get line:* |
||
put line |
put line |
||
end loop</ |
end loop</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang="tuscript"> |
||
$$ MODE TUSCRIPT |
$$ MODE TUSCRIPT |
||
Line 3,350: | Line 3,350: | ||
ENDLOOP |
ENDLOOP |
||
ENDACCESS q |
ENDACCESS q |
||
</syntaxhighlight> |
|||
</lang> |
|||
or: |
or: |
||
< |
<syntaxhighlight lang="tuscript"> |
||
LOOP line=datei |
LOOP line=datei |
||
PRINT line |
PRINT line |
||
ENDLOOP |
ENDLOOP |
||
</syntaxhighlight> |
|||
</lang> |
|||
Line 3,362: | Line 3,362: | ||
Taken from C++ U++ section |
Taken from C++ U++ section |
||
< |
<syntaxhighlight lang="cpp">#include <Core/Core.h> |
||
using namespace Upp; |
using namespace Upp; |
||
Line 3,371: | Line 3,371: | ||
while(in && !in.IsEof()) |
while(in && !in.IsEof()) |
||
Cout().PutLine(in.GetLine()); |
Cout().PutLine(in.GetLine()); |
||
}</ |
}</syntaxhighlight> |
||
Line 3,381: | Line 3,381: | ||
{{works with|Almquist Shell}} |
{{works with|Almquist Shell}} |
||
< |
<syntaxhighlight lang="bash"># This while loop repeats for each line of the file. |
||
# This loop is inside a pipeline; many shells will |
# This loop is inside a pipeline; many shells will |
||
# run this loop inside a subshell. |
# run this loop inside a subshell. |
||
Line 3,387: | Line 3,387: | ||
while IFS= read -r line ; do |
while IFS= read -r line ; do |
||
printf '%s\n' "$line" |
printf '%s\n' "$line" |
||
done</ |
done</syntaxhighlight> |
||
{{works with|Almquist Shell}} |
{{works with|Almquist Shell}} |
||
< |
<syntaxhighlight lang="bash"># This loop runs in the current shell, and can read both |
||
# the old standard input (fd 1) and input.txt (fd 3). |
# the old standard input (fd 1) and input.txt (fd 3). |
||
exec 3<input.txt |
exec 3<input.txt |
||
Line 3,397: | Line 3,397: | ||
printf '%s\n' "$line" |
printf '%s\n' "$line" |
||
done |
done |
||
exec 3>&-</ |
exec 3>&-</syntaxhighlight> |
||
{{works with|Bourne Shell}} |
{{works with|Bourne Shell}} |
||
< |
<syntaxhighlight lang="bash"># The old Bourne Shell interprets 'IFS= read' as 'IFS= ; read'. |
||
# It requires extra code to restore the original value of IFS. |
# It requires extra code to restore the original value of IFS. |
||
exec 3<input.txt |
exec 3<input.txt |
||
Line 3,410: | Line 3,410: | ||
done |
done |
||
IFS=$oldifs |
IFS=$oldifs |
||
exec 3>&-</ |
exec 3>&-</syntaxhighlight> |
||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
Reads the file "filename.txt" and outputs it to the console line by line. |
Reads the file "filename.txt" and outputs it to the console line by line. |
||
< |
<syntaxhighlight lang="ursa">decl file f |
||
f.open "filename.txt" |
f.open "filename.txt" |
||
while (f.hasline) |
while (f.hasline) |
||
out (in string f) endl console |
out (in string f) endl console |
||
end while</ |
end while</syntaxhighlight> |
||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
Reads and prints out file line by line: |
Reads and prints out file line by line: |
||
< |
<syntaxhighlight lang="vala"> |
||
public static void main(){ |
public static void main(){ |
||
var file = FileStream.open("foo.txt", "r"); |
var file = FileStream.open("foo.txt", "r"); |
||
Line 3,432: | Line 3,432: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang="vb">' Read a file line by line |
||
Sub Main() |
Sub Main() |
||
Dim fInput As String, fOutput As String 'File names |
Dim fInput As String, fOutput As String 'File names |
||
Line 3,450: | Line 3,450: | ||
Close #1 |
Close #1 |
||
Close #2 |
Close #2 |
||
End Sub 'Main</ |
End Sub 'Main</syntaxhighlight> |
||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
FilePath = "<SPECIFY FILE PATH HERE>" |
FilePath = "<SPECIFY FILE PATH HERE>" |
||
Set objFSO = CreateObject("Scripting.FileSystemObject") |
Set objFSO = CreateObject("Scripting.FileSystemObject") |
||
Line 3,462: | Line 3,462: | ||
objFile.Close |
objFile.Close |
||
Set objFSO = Nothing |
Set objFSO = Nothing |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Vedit macro language}}== |
=={{header|Vedit macro language}}== |
||
Line 3,471: | Line 3,471: | ||
This example reads the source code of this macro, |
This example reads the source code of this macro, |
||
copies it line by line into a new buffer and adds line numbers. |
copies it line by line into a new buffer and adds line numbers. |
||
< |
<syntaxhighlight lang="vedit">File_Open("line_by_line.vdm") |
||
#10 = Buf_Num // edit buffer for input file |
#10 = Buf_Num // edit buffer for input file |
||
#11 = Buf_Free // edit buffer for output |
#11 = Buf_Free // edit buffer for output |
||
Line 3,485: | Line 3,485: | ||
} |
} |
||
Buf_Close(NOMSG) // close the input file |
Buf_Close(NOMSG) // close the input file |
||
Buf_Switch(#11) // show the output </ |
Buf_Switch(#11) // show the output </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,510: | Line 3,510: | ||
===Simple version=== |
===Simple version=== |
||
{{works with|Visual Basic|VB6 Standard}} |
{{works with|Visual Basic|VB6 Standard}} |
||
< |
<syntaxhighlight lang="vb">' Read a file line by line |
||
Sub Main() |
Sub Main() |
||
Dim fInput As String, fOutput As String 'File names |
Dim fInput As String, fOutput As String 'File names |
||
Line 3,533: | Line 3,533: | ||
InputError: |
InputError: |
||
MsgBox "File: " & fInput & " not found" |
MsgBox "File: " & fInput & " not found" |
||
End Sub 'Main</ |
End Sub 'Main</syntaxhighlight> |
||
===Complex version=== |
===Complex version=== |
||
< |
<syntaxhighlight lang="vb">' Read lines from a file |
||
' |
' |
||
' (c) Copyright 1993 - 2011 Mark Hobley |
' (c) Copyright 1993 - 2011 Mark Hobley |
||
Line 3,668: | Line 3,668: | ||
Public Function btrim$(arg$) |
Public Function btrim$(arg$) |
||
btrim$ = LTrim$(RTrim$(arg$)) |
btrim$ = LTrim$(RTrim$(arg$)) |
||
End Function</ |
End Function</syntaxhighlight> |
||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
< |
<syntaxhighlight lang="vbnet">Imports System.IO |
||
' Loop through the lines of a file. |
' Loop through the lines of a file. |
||
Line 3,687: | Line 3,687: | ||
oReader.Close() |
oReader.Close() |
||
End Sub</ |
End Sub</syntaxhighlight> |
||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
< |
<syntaxhighlight lang="wart">with infile "x" |
||
drain (read_line)</ |
drain (read_line)</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="ecmascript">import "io" for File |
||
var lines = [] // store lines read |
var lines = [] // store lines read |
||
Line 3,716: | Line 3,716: | ||
} |
} |
||
System.print(lines.join("\n")) // print out lines</ |
System.print(lines.join("\n")) // print out lines</syntaxhighlight> |
||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
File is redirected on command line i.e: <file.txt |
File is redirected on command line i.e: <file.txt |
||
< |
<syntaxhighlight lang="xpl0">int C; |
||
[repeat repeat C:= ChIn(1); \repeat until end-of-line |
[repeat repeat C:= ChIn(1); \repeat until end-of-line |
||
ChOut(0, C); |
ChOut(0, C); |
||
until C < $20; \CR, LF, or EOF |
until C < $20; \CR, LF, or EOF |
||
until C = \EOF\ $1A; \repeat until end-of-file |
until C = \EOF\ $1A; \repeat until end-of-file |
||
]</ |
]</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
So many ways, here are a few |
So many ways, here are a few |
||
< |
<syntaxhighlight lang="zkl">foreach line in (File("foo.zkl")){print(line)}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="zkl">File("foo.zkl").pump(Console.print)</syntaxhighlight> |
||
< |
<syntaxhighlight lang="zkl">Utils.zipWith(False,fcn(a,b){"%d: %s".fmt(a,b).print()}, |
||
[0..],File("foo.zkl","r")) |
[0..],File("foo.zkl","r")) |
||
--> |
--> |
||
0: var R; n:=GarbageMan.gcCount; |
0: var R; n:=GarbageMan.gcCount; |
||
1: ref := GarbageMan.WeakRef(String("the","quick brown fox")); |
1: ref := GarbageMan.WeakRef(String("the","quick brown fox")); |
||
...</ |
...</syntaxhighlight> |