Read File to List
From Erlang Community
(Difference between revisions)
| Revision as of 02:44, 4 September 2006 (edit) Bfulgham (Talk | contribs) ← Previous diff |
Current revision (02:46, 4 September 2006) (edit) (undo) Bfulgham (Talk | contribs) |
||
| Line 19: | Line 19: | ||
| == Discussion == | == Discussion == | ||
| - | This recipe is suspiciously similar to [[Reading_Lines_from_a_File]]. For a more general solution, have a look at | + | 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: | 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: | ||
Current revision
[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

