Read a file line by line

Read a file line by line
You are encouraged to solve this task according to the task description, using any language you may know.

Read a file one line at a time, as opposed to reading the entire file at once.

360 Assembly

This program uses OS QSAM I/O macros (OPEN,CLOSE,GET,PUT,DCB).

*        Read a file line by line  12/06/2016READFILE CSECT         SAVE  (14,12)             save registers on entry         PRINT NOGEN         BALR  R12,0               establish addressability         USING *,R12               set base register         ST    R13,SAVEA+4         link mySA->prevSA         LA    R11,SAVEA           mySA         ST    R11,8(R13)          link prevSA->mySA         LR    R13,R11             set mySA pointer         OPEN  (INDCB,INPUT)       open the input file         OPEN  (OUTDCB,OUTPUT)     open the output fileLOOP     GET   INDCB,PG            read record         CLI   EOFFLAG,C'Y'        eof reached?         BE    EOF         PUT   OUTDCB,PG           write record         B     LOOPEOF      CLOSE (INDCB)             close input         CLOSE (OUTDCB)            close output         L     R13,SAVEA+4         previous save area addrs         RETURN (14,12),RC=0       return to caller with rc=0INEOF    CNOP  0,4                 end-of-data routine         MVI   EOFFLAG,C'Y'        set the end-of-file flag          BR    R14                 return to callerSAVEA    DS    18F                 save area for chainingINDCB    DCB   DSORG=PS,MACRF=PM,DDNAME=INDD,LRECL=80,                 *               RECFM=FB,EODAD=INEOFOUTDCB   DCB   DSORG=PS,MACRF=PM,DDNAME=OUTDD,LRECL=80,                *               RECFM=FBEOFFLAG  DC    C'N'                end-of-file flagPG       DS    CL80                buffer         YREGS         END   READFILE

8th

 "path/to/file" f:open ( . cr ) f:eachline f:close

with Ada.Text_IO;  use Ada.Text_IO; procedure Line_By_Line is   File : File_Type;begin   Open (File => File,         Mode => In_File,         Name => "line_by_line.adb");   loop      exit when End_Of_File (File);      Put_Line (Get_Line (File));   end loop;    Close (File);end Line_By_Line;
Output:
with Ada.Text_IO;  use Ada.Text_IO;

procedure Line_By_Line is
File : File_Type;
begin
Open (File => File,
Mode => In_File,
loop
exit when End_Of_File (File);
Put_Line (Get_Line (File));
end loop;

Close (File);
end Line_By_Line;


Aime

file f;text s; f_affix(f, "src/aime.c"); while (f_line(f, s) != -1) {    o_text(s);    o_byte('\n');}

ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extension to language used.
Works with: ALGOL 68G version Any - tested with release algol68g-2.3.5.
#!/usr/local/bin/a68g --script # FILE foobar;INT errno = open(foobar, "Read_a_file_line_by_line.a68", stand in channel); STRING line;FORMAT line fmt = $gl$; PROC mount next tape = (REF FILE file)BOOL: (  print("Please mount next tape or q to quit");  IF read char = "q" THEN done ELSE TRUE FI); on physical file end(foobar, mount next tape);on logical file end(foobar, (REF FILE skip)BOOL: done); FOR count DO  getf(foobar, (line fmt, line));  printf(($g(0)": "$, count, line fmt, line))OD;done: SKIP
Output:
1: #!/usr/local/bin/a68g --script #
2:
3: FILE foobar;
4: INT errno = open(foobar, "Read_a_file_line_by_line.a68", stand in channel);
5:
6: STRING line;
7: FORMAT line fmt = $gl$;
8:
9: PROC mount next tape = (REF FILE file)BOOL: (
10:   print("Please mount next tape or q to quit");
11:   IF read char = "q" THEN done ELSE TRUE FI
12: );
13:
14: on physical file end(foobar, mount next tape);
15: on logical file end(foobar, (REF FILE skip)BOOL: done);
16:
17: FOR count DO
18:   getf(foobar, (line fmt, line));
19:   printf(($g(0)": "$, count, line fmt, line))
20: OD;
21: done: SKIP


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 filetypesIf Errorlevel ; If no file selected	ExitApp ; --> Main loop: Input (File), Output (Text) Loop{FileReadLine, Line, %File%, %A_Index% ; Reads line N (where N is loop iteration)if Errorlevel ; If line does not exist, break loop	breakText .= A_Index ". " Line . "n" ; Appends the line to the variable "Text", adding line number before & new line after} ; --> Delivers the output as a text file FileDelete, Output.txt ; Makes sure output is clear before writingFileAppend, %Text%, Output.txt ; Writes the result to Output.txtRun Output.txt ; Shows the created file

AWK

Reading files line-by-line is the standard operation of awk.

One-liner:

Output:

Bracmat

fil 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.

Forth

4096 constant max-line : third ( A b c -- A b c A )  >r over r> swap ; : read-lines ( fileid -- )  begin  pad max-line third read-line throw  while  pad swap  ( fileid c-addr u )  \ string excludes the newline         2drop  repeat 2drop ;

Fortran

Usually, one reads a file with some idea what is in the file and some purpose behind reading it. For this task, suppose that the file just contains plain text, and the text is to be listed, line by line, to the end of the file. The remaining question is how long is the longest record? Some systems enable the reading of a record into a variable that is made big enough to hold whatever the record contains, though perhaps only up to some integer limit such as 65535. Fortran 2000 has formalised the provision of character variables whose size is determined when assigned to (as in TEXT = "This"//"That" where character variable TEXT is reallocated memory so as to hold eight characters, as needed for the assignment) but without a F2000 compiler to test, it is not clear that this arrangement will work for READ statements as well.

So one is faced again with the question "How long is a piece of string?" when choosing a predefined size. I have confronted a singularly witless format for supplying electricity data that would write up to an entire year's worth of half-hourly values to one line though it might be used to write just a few day's worth of data also. The header line specified the date and time slot for each column as Country,Island,Node,MEAN Energy,01AUG2010 Daily ENERGY,01AUG2010 01,01AUG2010 02,01AUG2010 03, etc. so all-in-all it was less trouble to specify CHARACTER*246810 for the input record scratchpad so as not to have to struggle with piecemeal input. In this example, change the value of ENUFF.

A common extension after F77 was the "Q" format, which returns the number of characters yet to be read in the input record. In its absence, one would have to just read the input with A format, and if the input record was shorter than ENUFF, then trailing spaces would be appended to ALINE and if ALINE was capacious then this would waste time. Similarly, for output, trailing spaces should be trimmed off, which means that if the input record contained trailing spaces, they would be lost. The scheme here, available via F90 is to use the Q format feature to determine how long the record is, then, request only that many characters to be placed in ALINE, and, write that many characters to the output which will thereby include any supplied trailing spaces. However, there must of course be no attempt to cram any more than ENUFF characters into ALINE, thus the MIN(L,ENUFF) in the READ statement, where the calculation is done on-the-fly. As well, should L be greater than ENUFF this is worth some remark, and in a way that cannot be confused with a listing line, each of which is prefixed by the record number. The default integer size is 32 bit so the numbers could be large but to avoid annoying blank space in the message, I0 format is used. Earlier Fortrans do not allow this, so one might specify I9.

On the other hand, the output device might be less than accommodating when presented with a line longer than it can print: lineprinters typically printed 120, 132 or maybe 144 characters to a line with anything beyond that ignored if it were not a cause for immediate termination. Thus, the WRITE statement could be augmented with ERR = label, END = label in hope of recovery attempts. If output were to a disc file, the END might be activated on running out of disc space but with windows the system would probably have crashed already. Given a long line to print a teletype printer would just hammer away at the last printing position, but more refined printers would start new lines as needed. I have used a dot-matrix printer that with lineprinter paper could be set to print some 360 cramped characters to a line, and have seen photographs of a special accountant's typewriter with a platen about four feet long. Then for spreadsheet users, there arrived a special printing prog, SIDEWAYS.

Peripheral to the task of reading a file line-by-line is the blather about specifying the file name and opening it. The OPEN statement allows for jumping to an ERR label (just as the READ statement has a jump for end-of-file), and carrying an IOSTAT value to specify the nature of the problem (invalid file name form, file access denied, etc.) but this is all very messy and the error codes are not the same across different systems either. I wish these statements were more like functions and returned TRUE/FALSE or a result code that could be tested in an IF-statement directly, as for example in Burroughs Algol where one could write something like While Read(in) Stuff Do ... ; - though a READ statement returned true for an I/O error, and false for success, so one defined Ican to be not and wrote While Ican Read(in) Stuff Do ... ;

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.

       INTEGER ENUFF		!A value has to be specified beforehand,.      PARAMETER (ENUFF = 2468)	!Provide some provenance.      CHARACTER*(ENUFF) ALINE	!A perfect size?      CHARACTER*66 FNAME	!What about file name sizes?      INTEGER LINPR,IN		!I/O unit numbers.      INTEGER L,N		!A length, and a record counter.      LOGICAL EXIST		!This can't be asked for in an "OPEN" statement.      LINPR = 6			!Standard output via this unit number.      IN = 10			!Some unit number for the input file.      FNAME = "Read.for"	!Choose a file name.      INQUIRE (FILE = FNAME, EXIST = EXIST)	!A basic question.      IF (.NOT.EXIST) THEN		!Absent?        WRITE (LINPR,1) FNAME		!Alas, name the absentee.    1   FORMAT ("No sign of file ",A)	!The name might be mistyped.        STOP "No file, no go."		!Give up.      END IF				!So much for the most obvious mishap.      OPEN (IN,FILE = FNAME, STATUS = "OLD", ACTION = "READ")	!For formatted input.       N = 0		!No records read so far.   10 READ (IN,11,END = 20) L,ALINE(1:MIN(L,ENUFF))	!Read only the L characters in the record, up to ENUFF.   11 FORMAT (Q,A)		!Q = "how many characters yet to be read", A = characters with no limit.      N = N + 1			!A record has been read.      IF (L.GT.ENUFF) WRITE (LINPR,12) N,L,ENUFF	!Was it longer than ALINE could accommodate?   12 FORMAT ("Record ",I0," has length ",I0,": my limit is ",I0)	!Yes. Explain.      WRITE (LINPR,13) N,ALINE(1:MIN(L,ENUFF))	!Print the record, prefixed by the count.   13 FORMAT (I9,":",A)		!Fixed number size for alignment.      GO TO 10			!Do it again.    20 CLOSE (IN)	!All done.      END	!That's all. 

An alternative approach would be to read the file as UNFORMATTED, just reading binary into some convenient scratchpad and then write the content to the output device, which would make what it could of the ASCII world's dithering between CR, CRLF, LFCR and CR as end-of-record markers. However, this would not be reading the file line-by-line.

FreeBASIC

' FB 1.05.0 Win64 Open "input.txt" For Input As #1Dim line_ As StringWhile Not Eof(1)  Line Input #1, line_  '' read each line  Print line_           '' echo it to the consoleWendClose #1PrintPrint "Press any key to quit"Sleep 

Frink

The lines 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.)

 for line = lines["file:yourfile.txt"]   println[line] 

Gambas

Public Sub Main() Dim hFile As FileDim sLine As String hFile = Open "../InputText.txt" For Input While Not Eof(hFile)  Line Input #hFile, sLine  Print sLineWend End

GAP

ReadByLines := function(name)	local file, line, count;	file := InputTextFile(name);	count := 0;	while true do		line := ReadLine(file);		if line = fail then			break;		fi;		count := count + 1;	od;	CloseStream(file);	return count;end; # With [http://www.ibiblio.org/pub/docs/misc/amnesty.txt amnesty.txt]ReadByLines("amnesty.txt"); # 384

Go

bufio.Scanner

The bufio package provides Scanner, a convenient interface for reading data such as a file of newline-delimited lines of text. Successive calls to the Scan method will step through the 'tokens' of a file, skipping the bytes between the tokens. The specification of a token is defined by a split function of type SplitFunc; the default split function breaks the input into lines with line termination stripped. Split functions are defined in this package for scanning a file into lines, bytes, UTF-8-encoded runes, and space-delimited words. The client may instead provide a custom split function.

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.

package main import (	"bufio"	"fmt"	"log"	"os") func init() {	log.SetFlags(log.Lshortfile)} func main() {	// Open an input file, exit on error.	inputFile, err := os.Open("byline.go")	if err != nil {		log.Fatal("Error opening input file:", err)	} 	// Closes the file when we leave the scope of the current function,	// this makes sure we never forget to close the file if the	// function can exit in multiple places.	defer inputFile.Close() 	scanner := bufio.NewScanner(inputFile) 	// scanner.Scan() advances to the next token returning false if an error was encountered	for scanner.Scan() {		fmt.Println(scanner.Text())	} 	// When finished scanning if any error other than io.EOF occured	// it will be returned by scanner.Err().	if err := scanner.Err(); err != nil {		log.Fatal(scanner.Err())	}} 

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.

package main import (    "bufio"    "fmt"    "io"    "log"    "os") func main() {    f, err := os.Open("file") // os.OpenFile has more options if you need them    if err != nil {           // error checking is good practice        // error *handling* is good practice.  log.Fatal sends the error        // message to stderr and exits with a non-zero code.        log.Fatal(err)    }     // os.File has no special buffering, it makes straight operating system    // requests.  bufio.Reader does buffering and has several useful methods.    bf := bufio.NewReader(f)     // there are a few possible loop termination    // conditions, so just start with an infinite loop.    for {        // reader.ReadLine does a buffered read up to a line terminator,        // handles either /n or /r/n, and returns just the line without        // the /r or /r/n.        line, isPrefix, err := bf.ReadLine()         // loop termination condition 1:  EOF.        // this is the normal loop termination condition.        if err == io.EOF {            break        }         // loop termination condition 2: some other error.        // Errors happen, so check for them and do something with them.        if err != nil {            log.Fatal(err)        }         // loop termination condition 3: line too long to fit in buffer        // without multiple reads.  Bufio's default buffer size is 4K.        // Chances are if you haven't seen a line terminator after 4k        // you're either reading the wrong file or the file is corrupt.        if isPrefix {            log.Fatal("Error: Unexpected long line reading", f.Name())        }         // success.  The variable line is now a byte slice based on on        // bufio's underlying buffer.  This is the minimal churn necessary        // to let you look at it, but note! the data may be overwritten or        // otherwise invalidated on the next read.  Look at it and decide        // if you want to keep it.  If so, copy it or copy the portions        // you want before iterating in this loop.  Also note, it is a byte        // slice.  Often you will want to work on the data as a string,        // and the string type conversion (shown here) allocates a copy of        // the data.  It would be safe to send, store, reference, or otherwise        // hold on to this string, then continue iterating in this loop.        fmt.Println(string(line))    }}

In comparison, ReadString is a little quick and dirty, but is often good enough.

package main import (    "bufio"    "fmt"    "io"    "log"    "os") func main() {    f, err := os.Open("file")    if err != nil {        log.Fatal(err)    }    bf := bufio.NewReader(f)    for {        switch line, err := bf.ReadString('\n'); err {        case nil:            // valid line, echo it.  note that line contains trailing \n.            fmt.Print(line)        case io.EOF:            if line > "" {                // last line of file missing \n, but still valid                fmt.Println(line)            }            return        default:            log.Fatal(err)        }    }}

Groovy

new File("Test.txt").eachLine { line, lineNumber ->    println "processing line $lineNumber:$line"}

Thanks to laziness, there's no difference between reading the file all at once and reading it line by line.

main = do  file <- readFile "linebyline.hs"  mapM_ putStrLn (lines file) 

Icon and Unicon

Line oriented I/O is basic. This program reads lines from "input.txt" into the variable line, but does nothing with it.

procedure main()f := open("input.txt","r") | stop("cannot open file ",fn)while line := read(f) close(f)end

J

J currently discourages this "read just one line" approach. In addition to the arbitrary character of lines, there are issues of problem size and scope (what happens when you have a billion characters between your newline delimiters?). Usually, it's easier to just read the entire file, or memory map the file, and when files are so large that that is not practical it's probably better to put the programmer in explicit control of issues like block sizes and exception handling.

This implementation looks for lines separated by ascii character 10. Lines returned here do not include the line separator character. Files with no line-separating character at the end are treated as well formed -- if the last character of the file is the line separator that means that you have an empty line at the end of the file.

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.

cocurrent 'linereader'   NB. configuration parameter  blocksize=: 400000   NB. implementation  offset=: 0  position=: 0  buffer=: ''  lines=: ''   create=: monad define    name=: boxxopen y    size=: 1!:4 name    blocks=: 2 <@(-~/\)\ ~. size <. blocksize * i. 1 + >. size % blocksize  )   readblocks=: monad define     if. 0=#blocks do. return. end.     if. 1<#lines do. return. end.     whilst. -.LF e.chars do.       buffer=: buffer,chars=. 1!:11 name,{.blocks       blocks=: }.blocks       lines=: <;._2 buffer,LF     end.     buffer=: _1{::lines  )   next=: monad define    if. (#blocks)*.2>#lines do. readblocks'' end.    r=. 0{::lines    lines=: }.lines    r  )
   example=: '/tmp/example.txt' conew 'linereader'   next__example''this is line 1   next__example''and this is line 2

Java

import java.io.BufferedReader;import java.io.FileReader; /** * Reads a file line by line, processing each line. * * @author  $Author$ * @version $Revision$ */public class ReadFileByLines {    private static void processLine(int lineNo, String line) {        // ...    }     public static void main(String[] args) {        for (String filename : args) {            BufferedReader br = null;            FileReader fr = null;            try {                fr = new FileReader(filename);                br = new BufferedReader(fr);                String line;                int lineNo = 0;                while ((line = br.readLine()) != null) {                    processLine(++lineNo, line);                }            }            catch (Exception x) {                x.printStackTrace();            }            finally {                if (fr != null) {                    try {br.close();} catch (Exception ignoreMe) {}                    try {fr.close();} catch (Exception ignoreMe) {}                }            }        }    }}
Works with: Java version 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:

for (String filename : args) {    try (FileReader fr = new FileReader(filename);BufferedReader br = new BufferedReader(fr)){        String line;        int lineNo = 0;        while ((line = br.readLine()) != null) {            processLine(++lineNo, line);        }    }    catch (Exception x) {        x.printStackTrace();    }}

fr and br 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 Files class (line numbers can be inferred from indices in the returned List):

import java.nio.file.Files;import java.nio.file.Paths;import java.nio.charset.Charset;import java.io.IOException;//...other class codeList<String> lines = null;try{    lines = Files.readAllLines(Paths.get(filename), Charset.defaultCharset());}catch(IOException | SecurityException e){    //problem with the file}

JavaScript

var fs = require("fs"); var readFile = function(path) {    return fs.readFileSync(path).toString();}; console.log(readFile('file.txt'));

jq

When invoked with the -R option, jq will read each line as a JSON string. For example:

$seq 0 5 | jq -R 'tonumber|sin'00.84147098480789650.90929742682568170.1411200080598672-0.7568024953079282-0.9589242746631385 In practice, this is of very limited use because each line is processed independently of all the others; it is more typical either to use the -R option in combination with the -s (--slurp) option, or to pipe the output of a "jq -R" process to another jq process. The combination of -R and -s results in the input being read as a single JSON string with embedded newline characters, and thus will not be discussed further here. The second alternative is illustrated by this example: $ seq 0 5 | jq -R 'tonumber|sin' | jq -s max0.9092974268256817

Julia

open("input_file","r") do f    for line in eachline(f)      println("read line: ", line)    endend

Kotlin

// version 1.1.2 import java.io.File fun main(args: Array<String>) {    File("input.txt").forEachLine { println(it) }}

Lasso

local(f) = file('foo.txt')handle => {#f->close}#f->forEachLine => {^     #1    '<br>' // note this simply inserts an HTML line break between each line.^}

Liberty BASIC

filedialog "Open","*.txt",file$if file$="" then endopen file$for input as #fwhile not(eof(#f)) line input #f, t$    print t$wendclose #f Mac filedialog "Open","*.txt",file$if file$="" then endopen file$ for input as #fwhile not(eof(#f))    t$= inputto$(#f, chr$(13)) print t$wendclose #f 

Unix

MATLAB / Octave

The function fgetl() read lines from file:

   fid = fopen('foobar.txt','r');  if (fid < 0) 	printf('Error:could not open file\n')  else	while ~feof(fid),		line = fgetl(fid);                %% process line %% 	end;        fclose(fid)  end; 

Maxima

/* Read a file and return a list of all lines */ readfile(name) := block(   [v: [ ], f: openr(name), line],   while stringp(line: readline(f)) do v: endcons(line, v),   close(f),   v)$ Mercury Basic version. :- module read_a_file_line_by_line.:- interface. :- import_module io. :- pred main(io::di, io::uo) is det. :- implementation. :- import_module int, list, require, string. main(!IO) :- io.open_input("test.txt", OpenResult, !IO), ( OpenResult = ok(File), read_file_line_by_line(File, 0, !IO) ; OpenResult = error(Error), error(io.error_message(Error)) ). :- pred read_file_line_by_line(io.text_input_stream::in, int::in, io::di, io::uo) is det. read_file_line_by_line(File, !.LineCount, !IO) :- % We could also use io.read_line/3 which returns a list of characters % instead of a string. io.read_line_as_string(File, ReadLineResult, !IO), ( ReadLineResult = ok(Line), !:LineCount = !.LineCount + 1, io.format("%d: %s", [i(!.LineCount), s(Line)], !IO), read_file_line_by_line(File, !.LineCount, !IO) ; ReadLineResult = eof ; ReadLineResult = error(Error), error(io.error_message(Error)) ). Version using a stream fold. :- module read_a_file_line_by_line.:- interface. :- import_module io. :- pred main(io::di, io::uo) is det. :- implementation. :- import_module int, list, require, string, stream. main(!IO) :- io.open_input("test.txt", OpenResult, !IO), ( OpenResult = ok(File), stream.input_stream_fold2_state(File, process_line, 0, Result, !IO), ( Result = ok(_) ; Result = error(_, Error), error(io.error_message(Error)) ) ; OpenResult = error(Error), error(io.error_message(Error)) ). :- pred process_line(line::in, int::in, int::out, io::di, io::uo) is det. process_line(line(Line), !LineCount, !IO) :- !:LineCount = !.LineCount + 1, io.format("%d: %s", [i(!.LineCount), s(Line)], !IO). NetRexx Using Java Scanner /* NetRexx */options replace format comments java crossref symbols nobinary parse arg inFileName . if inFileName = '' | inFileName = '.' then inFileName = './data/dwarfs.json'lines = scanFile(inFileName)loop l_ = 1 to lines[0] say l_.right(4)':' lines[l_] end l_ return -- Read a file and return contents as a Rexx indexed stringmethod scanFile(inFileName) public static returns Rexx fileLines = '' do inFile = File(inFileName) inFileScanner = Scanner(inFile) loop l_ = 1 while inFileScanner.hasNext() fileLines[0] = l_ fileLines[l_] = inFileScanner.nextLine() end l_ inFileScanner.close() catch ex = FileNotFoundException ex.printStackTrace end return fileLines  Using Java Reader /* NetRexx */options replace format comments java crossref symbols nobinary parse arg inFileName . if inFileName = '' | inFileName = '.' then inFileName = './data/dwarfs.json'lines = readFile(inFileName)loop l_ = 1 to lines[0] say l_.right(4)':' lines[l_] end l_ return -- Read a file and return contents as a Rexx indexed stringmethod readFile(inFileName) public static returns Rexx fileLines = '' inLine = String null inFileBR = BufferedReader null do inFile = File(inFileName) inFileBR = BufferedReader(FileReader(inFile)) loop l_ = 1 until inline = null inLine = inFileBR.readLine() if inline \= null then do fileLines[0] = l_ fileLines[l_] = inLine end end l_ catch exFNF = FileNotFoundException exFNF.printStackTrace catch exIO = IOException exIO.printStackTrace finally if inFileBR \= null then do do inFileBR.close() catch ex = IOException ex.printStackTrace end end end return fileLines  NewLISP  (set 'in-file (open "filename" "read"))(while (read-line in-file) (write-line)) (close in-file) Nim for line in lines "input.txt": echo line Objeck  bundle Default { class ReadFile { function : Main(args : String[]) ~ Nil { f := IO.FileReader->New("in.txt"); if(f->IsOpen()) { string := f->ReadString(); while(f->IsEOF() = false) { string->PrintLine(); string := f->ReadString(); }; f->Close(); }; } }}  Objective-C To read an entire file into a string, you can: NSString *path = [NSString stringWithString:@"/usr/share/dict/words"];NSError *error = nil;NSString *words = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];  Use the UTF-8 encoder on ASCII. Now to get the individual lines, break down the string: NSArray* lines = [words componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]; OCaml let () = let ic = open_in "input.txt" in try while true do let line = input_line ic in print_endline line done with End_of_file -> close_in ic But if we want to write a functional loading function we should remember that the try/with couple breaks the tail recursion. So we should externalise it outside of the loop in another function: let input_line_opt ic = try Some (input_line ic) with End_of_file -> None let read_lines ic = let rec aux acc = match input_line_opt ic with | Some line -> aux (line::acc) | None -> (List.rev acc) in aux [] let lines_of_file filename = let ic = open_in filename in let lines = read_lines ic in close_in ic; (lines) we use it like this: let () = let lines = lines_of_file "unixdict.txt" in List.iter print_endline lines Oforth : readFile(fileName) | line | File new(fileName) forEach: line [ line println ] ; OxygenBasic The core function GetFile reads the whole file:  function getline(string s, sys *i, *el) as string sys e e=instr i,s,chr(el) if e=0 then el=10 e=instr i,s,chr(el) 'files not using chr 13 end if if e=0 then e=len s e++ if el=13 then if asc(s,e)=10 then e++ 'crlf end if function = mid s,i,e-i i=eend function '====='TEST:'===== s=getfile "t.txt"i=1wr=""c=0el=13do wr = getline s,i,el if wr="" then exit do 'print wr c++end doprint "Line count " c  PARI/GP GP has an unfortunate limitations that prevents reading files line-by-line, but it's just as well since its file-handling capabilities are poor. The TODO file lists one desiderata as adding a t_FILE, which if added would presumably have support for this sort of operation. Thus the usual way of interacting with files in more than the simple way allowed by read is done by PARI with the usual C commands: FILE *f = fopen(name, "r");if (!f) { pari_err(openfiler, "input", name);}while(fgets(line, MAX_LINELEN, f) != NULL) { // ...} Pascal (* Read a file line by line *) program ReadFileByLine; var InputFile,OutputFile: File; TextLine: String; begin Assign(InputFile, 'c:\testin.txt'); Reset(InputFile); Assign(InputFile, 'c:\testout.txt'); Rewrite(InputFile); while not Eof(InputFile) do begin ReadLn(InputFile, TextLine); (* do someting with TextLine *) WriteLn(OutputFile, TextLine) end; Close(InputFile); Close(OutputFile) end. Perl For the simple case of iterating over the lines of a file you can do: open(my$fh, '<', 'foobar.txt')    || die "Could not open file: $!";while (<$fh>) { # each line is stored in $_, with terminating newline # chomp, short for chomp($_), removes the terminating newline    chomp;     process($_);}close$fh;

File encoding can be specified like:

open(my $fh, '< :encoding(UTF-8)', 'foobar.txt') || die "Could not open file:$!";

The angle bracket operator < > 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 $_, 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: open(my$fh, '<', 'foobar.txt')    || die "Could not open file: $!";while (my$line = <$fh>) { chomp$line;    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:

Rust

use std::io::{BufReader,BufRead};use std::fs::File; fn main() {    let file = File::open("file.txt").unwrap();    for line in BufReader::new(file).lines() {        println!("{}", line.unwrap());    }}
Output:
First line of the file!
Second line of the file!

Scala

import scala.io._Source.fromFile("foobar.txt").getLines.foreach(println)

Scheme

; Commented line below should be uncommented to use read-line with Guile;(use-modules (ice-9 rdelim)) (define file (open-input-file "input.txt"))(do ((line (read-line file) (read-line file))) ((eof-object? line))        (display line)        (newline))

Sed

Through a .sed file:

#!/bin/sed -fp 

or through a one-liner in bash:

 sed p filename 

TorqueScript

Read a file line by line:

 //Create a file object %f = new fileObject(); //Open and read a file %f.openForRead("PATH/PATH.txt"); while(!%f.isEOF()){	//Read each line from our file 	%line = %f.readLine();} //Close the file object %f.close(); //Delete the file object %f.delete(); 

  MODE TUSCRIPT datei="rosetta.txt"ERROR/STOP OPEN (datei,READ,-std-) ACCESS q: READ/RECORDS/UTF8 $datei s,line LOOP READ/NEXT/EXIT q PRINT line ENDLOOPENDACCESS q  or:  LOOP line=datei PRINT lineENDLOOP  UNIX Shell Redirect standard input from a file, and then use IFS= read -r line to read each line. mksh(1) manual says, "If read is run in a loop such as while read foo; do ...; done then leading whitespace will be removed (IFS) and backslashes processed. You might want to use while IFS= read -r foo; do ...; done for pristine I/O." Works with: Almquist Shell # This while loop repeats for each line of the file.# This loop is inside a pipeline; many shells will# run this loop inside a subshell.cat input.txt |while IFS= read -r line ; do printf '%s\n' "$line"done
Works with: Almquist Shell

Visual Basic .NET

Imports System.IO   ' Loop through the lines of a file.  ' Function assumes that the file exists.  Private Sub ReadLines(ByVal FileName As String)     Dim oReader As New StreamReader(FileName)    Dim sLine As String = Nothing     While Not oReader.EndOfStream      sLine = oReader.ReadLine()      ' Do something with the line.    End While     oReader.Close()   End Sub

Wart

with infile "x"  drain (read_line)

zkl

So many ways, here are a few

foreach line in (File("foo.zkl")){print(line)}
File("foo.zkl").pump(Console.print)
Utils.zipWith(False,fcn(a,b){"%d: %s".fmt(a,b).print()},      [0..],File("foo.zkl","r"))-->0: var R; n:=GarbageMan.gcCount;1: ref := GarbageMan.WeakRef(String("the","quick brown fox"));...`