Возможно, вам нужна комбинация file:open/2
и file:read_line/1
с включенной буферизацией.
Рифма:
$ cat mary_lamb.txt
Mary had a little lamb,
little lamb, little lamb,
Mary had a little lamb,
whose fleece was white as snow.
And everywhere that Mary went,
Mary went, Mary went,
and everywhere that Mary went,
the lamb was sure to go.
Исходный файл:
$ cat ./read_n_lines.erl
-module(read_n_lines).
-export([read_n_lines/2]).
read_n_lines(Filename,NumLines) ->
{ok, FileDev} = file:open(Filename,
[raw, read, read_ahead]),
Lines = do_read([],FileDev, NumLines),
file:close(FileDev),
Lines.
do_read(Lines, _, 0) ->
lists:reverse(Lines);
do_read(Lines, FileDev, L) ->
case file:read_line(FileDev) of
{ok, Line} ->
do_read([Line|Lines], FileDev, L - 1);
eof ->
do_read(Lines, FileDev, 0)
end.
raw
в Modes
, переданный в file:open/2
, обеспечивает более быстрый доступ к файлу, поскольку для обработки файла не требуется процесс Erlang.
Пример выполнения:
$ erl
1> c(read_n_lines).
{ok,read_n_lines}
2> Lines = read_n_lines:read_n_lines("./mary_lamb.txt", 5).
["Mary had a little lamb,\n","little lamb, little lamb,\n",
"Mary had a little lamb,\n",
"whose fleece was white as snow.\n",
"And everywhere that Mary went,\n"]
3> length(Lines).
5
4> read_n_lines:read_n_lines("./mary_lamb.txt", 666).
["Mary had a little lamb,\n","little lamb, little lamb,\n",
"Mary had a little lamb,\n",
"whose fleece was white as snow.\n",
"And everywhere that Mary went,\n",
"Mary went, Mary went,\n",
"and everywhere that Mary went,\n",
"the lamb was sure to go."]
5>
Чтобы удалить символ новой строки из строки, вы можете использовать string:strip/1,2,3
:
5> lists:map(fun(X) -> string:strip(X, right, $\n) end, Lines).
["Mary had a little lamb,","little lamb, little lamb,",
"Mary had a little lamb,",
"whose fleece was white as snow.",
"And everywhere that Mary went,"]
6>