s c h e m a t i c s : c o o k b o o k

/ Cookbook.FileCountLines

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Counting Lines in a File

Problem

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

Solution

(define (countlines filename)
  (call-with-input-file filename
    (lambda (p)
      (let loop ((line (read-line p))
                 (result 0))
        (if (eof-object? line)
            result
            (loop (read-line p) (+ 1 result)))))))

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:

(define (fold-file-lines filename knil kons)
(call-with-input-file filename
    (lambda (p)
      (let loop ((line (read-line p))
                 (result knil))
        (if (eof-object? line)
            result
            (loop (read-line p) (kons line result)))))))

Now we can redefine countlines and readlines like so:

(define (countlines fname) 
  (fold-file-lines fname 0 
                   (lambda (line result) (+ 1 result))))

(define (readlines fname) 
  (reverse 
   (fold-file-lines fname '() cons)))


Comments about this recipe

A solution using regular expressions directly on the input stream:

(define count-lines 
  (let ([re (regexp ".*?((\n\r)|(\r\n)|\n|\r|$)")])   ; *? shortest possible
    (lambda (filename)
      (call-with-input-file filename
        (lambda (in)
          (let loop ([l 0])
            (cond
              [(eof-object? (peek-char in))  l]
              [(regexp-match re in)          (loop (+ l 1))]
              [else                          (loop l)])))))))

-- JensAxelSoegaard - 21 Aug 2004

Contributors

-- GordonWeakliem - 13 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: FileRecipes
TopicOrder: 080

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, 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