Erlang Language File I/O Reading from a file


Let's assume you have a file lyrics.txt which contains the following data:

summer has come and passed
the innocent can never last
wake me up when september ends

Read the entire file at a time

By using file:read_file(File), you can read the entire file. It's an atomic operation:

1> file:read_file("lyrics.txt").
{ok,<<"summer has come and passed\r\nthe innocent can never last\r\nWake me up w
hen september ends\r\n">>}

Read one line at a time

io:get_line reads the text until the newline or the end of file.

1> {ok, S} = file:open("lyrics.txt", read).
2> io:get_line(S, '').
"summer has come and passed\n"
3> io:get_line(S, '').
"the innocent can never last\n"
4> io:get_line(S, '').
"wake me up when september ends\n"
5> io:get_line(S, '').
6> file:close(S).

Read with the random access

file:pread(IoDevice, Start, Len) reads from Start as much as Len from IoDevice.

1> {ok, S} = file:open("lyrics.txt", read).
2> file:pread(S, 0, 6).
3> file:pread(S, 7, 3).