Files
lisplings/exercises/21_files/files1.lisp
T

37 lines
1.2 KiB
Common Lisp

;;; FILES 1: WITH-OPEN-FILE
;;;
;;; (with-open-file (stream path :direction :output) body) opens a
;;; file, runs the body, and closes the file afterwards - even when
;;; the body signals an error. :DIRECTION decides which way the
;;; stream flows: :output writes, and the default is :input.
;;;
;;; FORMAT's first argument can be a stream instead of NIL: the
;;; output lands in the file instead of a string.
;;;
;;; (format nil "...") => a string
;;; (format out "...") => into the file
;;;
;;; READ pulls ONE s-expression off a stream: the same reader that
;;; reads your code, reading the file's text instead.
(defparameter *note-file* "lisplings-note.txt")
;; TODO: Write the list (lisp is lovely) to *NOTE-FILE*, then
;; return T so the check below can see the save worked.
(defun save-note ()
(with-open-file (out *note-file*)
(format out "(lisp is lovely)~%")
t))
;; TODO: READ the list back out of *NOTE-FILE*.
(defun load-note ()
(read *note-file*))
;;; ------------------------------------------------------------------
;;; Checks. Read them - they tell you what to aim for - but leave
;;; them unchanged.
;;; ------------------------------------------------------------------
(check (save-note))
(check-equal '(lisp is lovely) (load-note))