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



Related tasks

 Read a file character by character
 Input loop.


:- 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))
    ).