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

/ Cookbook.FileAppendFiles

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

Appending Files Together

Problem

You want to append the contents of several files to a single file. For example you want the contents of the file foo.txt to be the contents of bar.txt and baz.txt. In the UNIX shell you might write:

cat bar.txt baz.txt > foo.txt

Solution

The function file-append does the job:

(require (lib "port.ss"))

;; file-append : (U path string) ... -> void
;;
;; Copys the contents of the src files to dest
(define (file-append dest . src)
  (with-output-to-file dest
    (lambda ()
      (copy-port
       (apply input-port-append #t (map open-input-file src))
       (current-output-port)))))

The key parts of this function are the calls to input-port-append and copy-port. Using input-port-append we first make one input port that returns in succession the data contained in each src file. We then efficiently copy the data to the output port using copy-port. The #t parameter to input-port-append tells it to close the given ports when they reach the end of the file.

Discussion

The functions used in this example have many uses outside of copying files. For example, to efficiently copy the contents of a port to a string you could use copy-port and open-output-string. See FileRead for more examples.


Comments about this recipe

Contributors

-- NoelWelsh - 04 Jan 2007

CookbookForm
TopicType: Recipe
ParentTopic: FileRecipes
TopicOrder: 999

 
 
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