Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

erlang

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.

like image 509
Konstantin Avatar asked Jan 31 '10 10:01

Konstantin


2 Answers

{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.
like image 105
Zed Avatar answered Oct 21 '22 02:10

Zed


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)].
like image 36
ja. Avatar answered Oct 21 '22 00:10

ja.