tags:

views:

117

answers:

3

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.

A: 

Is not an answer, but I think that read whole file to a list of 'string's is a bad idea. Also I be glad to recommend to use async io, but don't know how Erlang support it (I just learning Erlang).

W55tKQbuRu28Q4xv
+1  A: 
{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.
Zed
+1  A: 

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)].
ja