Read File to List
From Erlang Community
Problem
You want to read the lines from a file and store them in a list.
Solution
readlines(FileName) ->
{ok, Device} = file:open(FileName, [read]),
get_all_lines(Device, []).
get_all_lines(Device, Accum) ->
case io:get_line(Device, "") of
eof -> file:close(Device), Accum;
Line -> get_all_lines(Device, Accum ++ [Line])
end.
|
Discussion
This recipe is suspiciously similar to FileReadingLines. For a more general solution, have a look at FileCountLines.
This recipe can be rather slow for larger files. The problem is that the append operation must traverse the list in order to append the new line. As the list grows, this takes longer and longer. It is probably better to build the list in reverse order and then reverse it at the end:
get_all_lines(Device, Accum) ->
case io:get_line(Device, "") of
eof -> file:close(Device), lists:reverse(Accum);
Line -> get_all_lines(Device, [Line|Accum])
end.
|

Digg It
Del.icio.us
Reddit
Facebook
Stumble Upon
Technorati

