Scheme files
last modified November 25, 2026 Guile 3.0
A file is read and written through a port, like the terminal and strings in
the ports and output and
reading input articles. The only new
step is opening the port on a file, and closing it when the work is done.
Once a file port is open, display, write,
read-line, and the other procedures work on it as usual. The
examples run with GNU Guile 3.0.7 and work with files in the current
directory.
Writing a file
call-with-output-file opens a file for writing, calls a
procedure with the port, and closes the port when the procedure returns. If
the file exists, its old content is replaced.
(call-with-output-file "towns.txt"
(lambda (port)
(display "Bratislava" port)
(newline port)
(display "Kosice" port)
(newline port)
(display "Presov" port)
(newline port)
(write '(population 475000) port)
(newline port)))
(display "towns.txt written")
(newline)
The procedure writes three town names, each followed by a newline, and a
list with write. The port is passed to every output call; the
final message has no port argument, so it goes to the terminal. The
cat command shows what the file contains.
$ guile writing.scm towns.txt written $ cat towns.txt Bratislava Kosice Presov (population 475000)
Reading a file
call-with-input-file is the counterpart for reading. It opens
the file, passes the input port to a procedure, closes the port, and returns
the result of the procedure.
(use-modules (ice-9 rdelim))
(define (read-lines port)
(let loop ((line (read-line port)) (acc '()))
(if (eof-object? line)
(reverse acc)
(loop (read-line port) (cons line acc)))))
(define lines (call-with-input-file "towns.txt" read-lines))
(display (length lines))
(display " lines")
(newline)
(let loop ((lines lines) (n 1))
(unless (null? lines)
(display n)
(display ": ")
(display (car lines))
(newline)
(loop (cdr lines) (+ n 1))))
read-lines collects the lines of a port into a list, using the
loop from the reading input article with an explicit port. It already has
the right shape, a procedure of one port, so it is passed to
call-with-input-file directly. The rest of the program numbers
the lines. Reading a file into a list of lines is a convenient first step
for files that fit into memory.
$ guile reading.scm 4 lines 1: Bratislava 2: Kosice 3: Presov 4: (population 475000)
Redirecting the current ports
with-output-to-file and with-input-from-file call
a procedure without arguments and make the file its current output or input
port. Code that prints to the standard output or reads from the standard
input then works with a file without any changes.
(use-modules (ice-9 rdelim))
(define (print-squares n)
(do ((i 1 (+ i 1)))
((> i n))
(display i)
(display " ")
(display (* i i))
(newline)))
(with-output-to-file "squares.txt"
(lambda () (print-squares 6)))
(define (sum-second-column)
(let loop ((line (read-line)) (sum 0))
(if (eof-object? line)
sum
(let ((fields (string-split line #\space)))
(loop (read-line)
(+ sum (string->number (cadr fields))))))))
(display (with-input-from-file "squares.txt" sum-second-column))
(newline)
print-squares prints a table of numbers and their squares to
the current output port. Inside with-output-to-file the table
goes to squares.txt. sum-second-column reads from
the current input port, which with-input-from-file connects to
the same file, and adds up the squares. The ports are restored afterwards,
so the sum is printed to the terminal.
$ guile redirect.scm 91 $ cat squares.txt 1 1 2 4 3 9 4 16 5 25 6 36
Opening and closing ports
The call-with procedures suit work on one file. When a program
reads one file and writes another, it can open both ports with
open-input-file and open-output-file and close
them with close-port. Closing an output port writes out the
data still in its buffer and releases the file. Guile also flushes open
ports when a program ends, but until then another program reading the file
may not see all of the data, so ports should be closed as soon as the work
is done.
(use-modules (ice-9 rdelim))
(define in (open-input-file "towns.txt"))
(define out (open-output-file "towns-upper.txt"))
(let loop ((line (read-line in)) (count 0))
(if (eof-object? line)
(begin
(display count)
(display " lines copied")
(newline))
(begin
(display (string-upcase line) out)
(newline out)
(loop (read-line in) (+ count 1)))))
(close-port in)
(close-port out)
The program copies towns.txt line by line into
towns-upper.txt and converts each line to upper case on the
way. Only one line is in memory at a time, so this approach works for files
of any size. Both ports are closed after the loop.
$ guile uppercase.scm 4 lines copied $ cat towns-upper.txt BRATISLAVA KOSICE PRESOV (POPULATION 475000)
Appending to a file
call-with-output-file always starts with an empty file. To add
lines to the end of an existing file, it is opened with Guile's
open-file procedure in mode "a", for append. The
mode string comes from C: "r" reads, "w" writes,
and "a" appends. A file opened for appending is created if it
does not exist.
(use-modules (ice-9 rdelim))
(define (count-lines file)
(if (file-exists? file)
(call-with-input-file file
(lambda (port)
(let loop ((n 0))
(if (eof-object? (read-line port))
n
(loop (+ n 1))))))
0))
(define (log-message file text)
(let ((port (open-file file "a")))
(display (+ (count-lines file) 1) port)
(display ". " port)
(display text port)
(newline port)
(close-port port)))
(log-message "log.txt" "program started")
(log-message "log.txt" "work done")
(display (count-lines "log.txt"))
(display " entries in log.txt")
(newline)
log-message numbers each entry by counting the lines that the
file already has. count-lines checks with
file-exists? first, because opening a missing file for reading
is an error. Each run adds two entries, so the program is run twice and the
numbering continues.
$ guile logbook.scm 2 entries in log.txt $ guile logbook.scm 4 entries in log.txt $ cat log.txt 1. program started 2. work done 3. program started 4. work done
Copying, renaming, and deleting
Guile provides procedures that operate on whole files without opening them:
copy-file, rename-file, which also moves a file
within a file system, and delete-file.
(define (show-status . files)
(for-each (lambda (file)
(display file)
(display (if (file-exists? file) " exists" " missing"))
(newline))
files))
(copy-file "towns.txt" "backup.txt")
(show-status "towns.txt" "backup.txt")
(rename-file "backup.txt" "archive.txt")
(show-status "backup.txt" "archive.txt")
(delete-file "archive.txt")
(show-status "archive.txt")
The program copies towns.txt to a backup, renames the backup,
and deletes it. show-status takes any number of file names as
a rest argument and reports for each one whether it exists. All three
procedures replace or remove files without asking, so they deserve care in
real programs. Working with directories is the topic of the
directories article.
$ guile manage.scm towns.txt exists backup.txt exists backup.txt missing archive.txt exists archive.txt missing
Missing files
Opening a file that does not exist, or that the program may not read, raises
an error. Checking with file-exists? first leaves a gap in
which the file can disappear, so programs usually catch the error instead,
with guard from the exceptions
article.
(use-modules (ice-9 exceptions) (ice-9 textual-ports))
(define (read-file-or-default file default)
(guard (e ((error? e)
(display "cannot read ")
(display file)
(display ": ")
(display (car (exception-irritants e)))
(newline)
default))
(call-with-input-file file get-string-all)))
(write (read-file-or-default "towns-upper.txt" ""))
(newline)
(write (read-file-or-default "config.txt" "(default)"))
(newline)
(call-with-input-file "nothing.txt" get-string-all)
read-file-or-default reads a whole file with
get-string-all and returns a default value when that fails.
Guile reports the failed system call as an error whose first irritant is the
message of the operating system. The file towns-upper.txt
exists, config.txt does not. The last line opens a missing file
without a guard, and the program stops with a two-line error
message; the output omits the backtrace.
$ guile missing.scm "BRATISLAVA\nKOSICE\nPRESOV\n(POPULATION 475000)\n" cannot read config.txt: No such file or directory "(default)" ERROR: In procedure open-file: In procedure open-file: No such file or directory: "nothing.txt"
Processing a data file
A typical task reads a data file, computes something, and writes the result to another file. The input here is a CSV file of sales with a category, a product, and an amount on each line.
(use-modules (ice-9 rdelim))
(define (add-amount totals category amount)
(let ((entry (assoc category totals)))
(if entry
(begin
(set-cdr! entry (+ (cdr entry) amount))
totals)
(append totals (list (cons category amount))))))
(define (read-totals port)
(let loop ((line (read-line port)) (totals '()))
(if (eof-object? line)
totals
(let ((fields (string-split line #\,)))
(loop (read-line port)
(add-amount totals
(car fields)
(string->number (caddr fields))))))))
(define totals (call-with-input-file "sales.csv" read-totals))
(call-with-output-file "summary.txt"
(lambda (port)
(for-each (lambda (entry)
(display (car entry) port)
(display ": " port)
(display (cdr entry) port)
(newline port))
totals)
(display "total: " port)
(display (apply + (map cdr totals)) port)
(newline port)))
(display (length totals))
(display " categories written to summary.txt")
(newline)
read-totals reads the lines of a port and adds each amount to
its category in an association list; add-amount updates an
existing entry with set-cdr! or appends a new one, so the
categories keep the order in which they first appear. The totals are then
written to summary.txt with a grand total at the end.
$ cat sales.csv fruit,apples,12 fruit,pears,8 vegetables,carrots,20 fruit,plums,15 bakery,bread,6 vegetables,onions,9 bakery,rolls,30 $ guile summary.scm 3 categories written to summary.txt $ cat summary.txt fruit: 35 vegetables: 29 bakery: 36 total: 100
Binary files
Text ports convert between characters and bytes with an encoding. Binary
data, such as images, is read and written as bytes instead, with the binary
ports of the (rnrs io ports) module and the
bytevectors that hold the bytes.
(use-modules (rnrs bytevectors) (rnrs io ports))
(define data (u8-list->bytevector '(137 80 78 71 0 255 16 32)))
(call-with-port (open-file-output-port "data.bin")
(lambda (port)
(put-bytevector port data)))
(define loaded
(call-with-port (open-file-input-port "data.bin")
get-bytevector-all))
(display (bytevector-length loaded))
(display " bytes: ")
(display (bytevector->u8-list loaded))
(newline)
(display (bytevector=? data loaded))
(newline)
open-file-output-port opens a binary output port, and
put-bytevector writes the eight bytes, which begin like the
header of a PNG image. call-with-port closes the port after the
procedure returns. get-bytevector-all reads the whole file back
into a new bytevector, and bytevector=? confirms that the bytes
are unchanged. The od command shows the file in decimal.
$ guile binary.scm 8 bytes: (137 80 78 71 0 255 16 32) #t $ od -A d -t u1 data.bin 0000000 137 80 78 71 0 255 16 32 0000008
Source
File Ports — GNU Guile Reference Manual
Binary I/O — GNU Guile Reference Manual
In this article we have written and read text files with
call-with-output-file and call-with-input-file,
redirected the current ports to files, opened and closed ports by hand,
appended to a file, copied, renamed, and deleted files, handled missing files
with guard, summarised a CSV file into a new file, and written
and read binary data. The association
lists article covers the structure used for the totals, and the
modules article shows how to move helpers
such as read-lines into a module of their own.
Author
List all Scheme tutorials.