从erlang中读取文本文件到二进制字符串列表所花费的时间最有效的方法是什么?显而易见的解决方案
-module(test).
-export([run/1]).
open_file(FileName, Mode) ->
{ok, Device} = file:open(FileName, [Mode, binary]),
Device.
close_file(Device) ->
ok = file:close(Device).
read_lines(Device, L) ->
case io:get_line(Device, L) of
eof ->
lists:reverse(L);
String ->
read_lines(Device, [String | L])
end.
run(InputFileName) ->
Device = open_file(InputFileName, read),
Data = read_lines(Device, []),
close_file(Device),
io:format("Read ~p lines~n", [length(Data)]).
当文件包含超过100000行时,变得太慢。
答案 0 :(得分:16)
{ok, Bin} = file:read_file(Filename).
或者如果你需要逐行内容
read(File) ->
case file:read_line(File) of
{ok, Data} -> [Data | read(File)];
eof -> []
end.
答案 1 :(得分:2)
将整个文件读入二进制文件。转换为列表并删除行。
这比任何其他方法都更有效。如果你不相信我的时间 它
file2lines(File) -> {ok, Bin} = file:read_file(File), string2lines(binary_to_list(bin), []). string2lines("\n" ++ Str, Acc) -> [reverse([$\n|Acc]) | string2lines(Str,[])]; string2lines([H|T], Acc) -> string2lines(T, [H|Acc]); string2lines([], Acc) -> [reverse(Acc)].