Alex Rivera | Logout

The most efficient way to read a file into a list of strings

Asked 2010-01-31T10:25:44.170
10

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.

Edit
Report

1 Answer

3

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)].
answered 2010-02-02T16:08:32.670

Your Answer