从文件中读取

假设你有一个文件 lyrics.txt ,其中包含以下数据:

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

一次读取整个文件

通过使用 file:read_file(File),你可以读取整个文件。这是一个原子操作:

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">>}

一次读一行

io:get_line 读取文本直到换行符或文件结尾。

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

阅读随机访问

file:pread(IoDevice, Start, Len)Start 读取与 Len 一样多的 Len

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"}