Erlang Language File I/O Reading from a file


Example

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).
{ok,<0.57.0>}
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, '').
eof
6> file:close(S).
ok

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).
{ok,<0.57.0>}
2> file:pread(S, 0, 6).
{ok,"summer"}
3> file:pread(S, 7, 3).
{ok,"has"}