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

/ Erlang.FileCountLines

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

Counting Lines in a File

Problem

You need to count how many lines are in a file.

Solution

int_countlines(Device, Result) ->
    case io:get_line(Device, "") of
        eof  -> file:close(Device), Result;
        Line -> int_countlines(Device, Result + 1)
    end.
    
countlines(FileName) ->
    {ok, Device} = file:open(FileName,[read]),
    int_countlines(Device, 0).
Which yields the following, when applied to the test file "cookbook.erl":
1> countlines("cookbook.erl").
82
But doesn't this look strikingly like FileRead?

Discussion

There seems to be a pattern here: open a text file, do something with each line, return the result. Let's define fold-file-lines to abstract this pattern:

int_fold_lines(Device, Kons, Result) ->
    case io:get_line(Device, "") of
        eof  -> file:close(Device), Result;
   Line -> NewResult = Kons(Line, Result),
                int_fold_lines(Device, Kons, NewResult)
    end.

fold_file_lines(FileName, Kons, Knil) ->
    {ok, Device} = file:open(FileName,[read]),
    int_fold_lines(Device, Kons, Knil).

Now we can redefine countlines and readlines like so:

countlines(FileName) ->
  fold_file_lines(FileName, fun(L,R) -> R + 1 end, 0).

readlines(FileName) ->
    fold_file_lines("cookbook.erl", fun(L,R) -> R ++ [L] end, []).


Comments about this recipe

Contributors

Based on work by GordonWeakliem.

-- BrentAFulgham - 03 Sep 2004

CookbookForm
TopicType: Recipe
ParentTopic: FileRecipes
TopicOrder: 080

 
 
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