從檔案中讀取

假設你有一個檔案 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"}