PreviousUpNext

5.5.45  Read a text file

The simplest way to read a text file foo.txt as a list of lines is to use the lines function from the file package:

    line_list = file::as_lines "foo.txt";

Thus, for example, a quick and easy way to print out the contents of a file is

    foreach (file::as_lines "foo.txt") {. print #line; };

If you like to see more of what is going on under the hood, file::as_lines is equivalent to

    fun lines filename
        =
        {    fd = file::open_for_read filename;
             line_list = file::read_lines fd;
             file::close_input fd;
             line_list;
        };

where in turn file::read_lines is equivalent to

    fun read_lines input_stream
        =
        read_lines' (input_stream, [])
        where
            fun read_lines' (input_stream, lines_so_far)
                =
                case (file::read_line input_stream)
                    NULL     => reverse lines_so_far; 
                    THE line => read_lines' (input_stream, line ! lines_so_far);
                esac;
        end;

If you want to trap failures to open the specified file, issue an error message, and continue, you can write

    fun lines filename
        =
        {    fd = file::open_for_read filename;
             line_list = file::read_lines fd;
             file::close_input fd;
             line_list;
        }
        except io_exceptions::IO _
            =
            {   fprintf stderr "Could not open %s to read, treating it as empty.\n" filename;
                [];
            };

Comments and suggestions to: bugs@mythryl.org

PreviousUpNext