Read File to List
From Erlang Community
[edit] Problem
You want to read the lines from a file and store them in a list.
[edit] 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.
|
[edit] Discussion
This recipe is suspiciously similar to Reading_Lines_from_a_File. For a more general solution, have a look at Count_Lines_in_a_File.
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

