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.

Solution

500 Can't connect to 127.0.0.1:8778 (connect: Connection refused)

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 afterwards, you can define the following:

500 Can't connect to 127.0.0.1:8778 (connect: Connection refused)

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.

Comparison with Python: readlines corresponds to File.readlines() and read-all to File.read().


Comments about this recipe

See another approach in FileReadingLines

another approach

this will work and not be subject to race conditions (all of the heavy lifting is in copy-port):

500 Can't connect to 127.0.0.1:8778 (connect: Connection refused)

but I do not recommend reading files into strings. Instead, it is much better to just operate on the port if you possibly can.

-- http://list.cs.brown.edu/pipermail/plt-scheme/2008-November/028271.html

It's worth reading the thread.

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