e r l a n g : c o o k b o o k

/ FileRead / Erlang.FileRead

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Reading An Entire Text File

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.


Comments about this recipe

Contributors

Based on work by GordonWeakliem.

-- BrentAFulgham - 03 Sep 2004

-- MarkWutka - 07 Feb 2006 (Added reverse list accumulation)

CookbookForm
TopicType: Recipe
ParentTopic: FileRecipes
TopicOrder: 070

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest