What is the most efficient way from the time consumed to read a text file into a list of binary strings in erlang ? The obvious solution
-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)]).
becomes too slow when the file contains more than 100000 lines.
{ok, Bin} = file:read_file(Filename).
or if you need the contents line by line
read(File) ->
case file:read_line(File) of
{ok, Data} -> [Data | read(File)];
eof -> []
end.
read the entire file in into a binary. Convert to a list and rip out the lines.
This is far more efficient than any other method. If you don't believe me time it.
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)].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With