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

/ Cookbook.FileRead

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

Reading An Entire Text File

Problem

You want to read the lines from a file and store them in a list, the way Python's File.readlines() does.

Solution

(define (readlines filename)
  (call-with-input-file filename
    (lambda (p)
      (let loop ((line (read-line p))
                 (result '()))
        (if (eof-object? line)
            (reverse result)
            (loop (read-line p) (cons line result)))))))

Discussion

call-with-input-file is an R5RS procedure that takes an arbitrary procedure of one argument and returns the result of that procedure. The port opened by call-with-input-file will be closed upon return from the procedure given in the 2nd argument, however if the procedure never returns, the port won't be closed. The MzScheme call-with-input-file* function will close the port even if control leaves the procedure passed to it.

Of course, if you want to read everything into a big string and process the string (like calling File.read() in Python), you can define the following:

(define (read-all path)
    (let ((size (file-size path)))
      (call-with-input-file path
        (lambda (p)
          (read-string size p)))))

MzScheme's call-with-input-file accepts a third argument which allows you to specify 'text or 'binary, 'text is used to handle platform differences in newlines.

Don't be fooled by read. read is for reading S-Expressions from a port (i.e. Scheme code). readline and read-string are for reading raw text.


Comments about this recipe

See another approach in FileReadingLines

Contributors

-- GordonWeakliem - 13 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: FileRecipes
TopicOrder: 1

 
 
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