Read File to List Alternate

From Erlang Community

(Difference between revisions)
Revision as of 05:46, 12 January 2007 (edit)
Patricknharris (Talk | contribs)

← Previous diff
Current revision (16:06, 13 June 2007) (edit) (undo)
Defza (Talk | contribs)
m (Solution - fixed unbound variable B supposed to be Binary)
 
Line 11: Line 11:
readfile(FileName) -> readfile(FileName) ->
{ok, Binary} = file:read_file(FileName), {ok, Binary} = file:read_file(FileName),
- Lines = string:tokens(erlang:binary_to_list(B), "\n").+ Lines = string:tokens(erlang:binary_to_list(Binary), "\n").
</code> </code>
[[Category:CookBook]][[Category:FileRecipes]] [[Category:CookBook]][[Category:FileRecipes]]

Current revision

[edit] Problem

You want to read the lines from a file and store them in a list, efficiently.

[edit] Discussion

I read somewhere a while back, possibly in Joe Armstrong's book that an alternative, efficient approach for converting the file contents to a list is to read the file into a binary, since that is a BIF routine, and then converting the binary to a list.

[edit] Solution

readfile(FileName) ->
    {ok, Binary} = file:read_file(FileName),
     Lines = string:tokens(erlang:binary_to_list(Binary), "\n").
Erlang/OTP Projects
Personal tools