Erlang Central

Difference between revisions of "Read File to List"

From ErlangCentral Wiki

 
(One intermediate revision by one user not shown)
Line 19:Line 19:
 
== Discussion ==
 
== Discussion ==
  
This recipe is suspiciously similar to FileReadingLines. For a more general solution, have a look at FileCountLines.
+
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:

Revision as of 02:46, 4 September 2006

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 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.