入出力::CommonLisp

11.5 ファイル・システム

ファイルとxストリームを結びつける方法.
ファイル名からそのファイルに対するストリームを得るには,
openという関数を用いる.
openはファイル名を引数として取る.
>(setq stream (open "foo.lisp"))
とするとstreamという変数に,foo.lispというファイルに結びついたストリームが代入される.

何も指定しないと入力ストリームが返される.
出力用のストリームがほしい時には,:directionというキーワード・パラメータの値を:outputというキーワードにする.
(setq another-steram
   (open "bar.lisp" :direction :output)
bar.lispというファイルが存在しなければ,
新しく作られる.
もし存在していれば,消される.
それがいやなら,
(setq another-stream
   (open "bar.lisp" :direction :output
                    :if-exists :append))
とすれば,以前の内容に続けて出力される.

ファイルの入出力処理が終わったら,closeという関数を使いファイルを閉じる.
(close another-stream)
closeは忘れられることが多いため,with-open-fileというマクロを用いるのがよい. (do* (
(with-open-file (変数 ファイル名
                 オプション ... オプション)
   式 ... 式)
挙動は,まずファイル名のファイルがopenされ,
そのファイルに対するストリームがバインドされる.
そして式...式が順に評価されて,そのあとでストリームが自動的にcloseされる.

ファイルへの出力例

0から99までの階乗の値がbar.lispに出力される.
(with-open-file (stream "bar.lisp"
                  :direction :output)
  (dotimes (i 10
(with-op0)
    (print (fact i) stream)))

ファイルからの入力例

foo.lispの中の式が順に評価されていく.
(with-open-file (stream "foo.lisp")
  (do* ((eos (cons nil nil))
        (x (read stream nil eos)
           (read stream nil eos)))
       ((eq x eos))
     (eval x)))
readの一般形
(read ストリーム nil 終値)
よく使う終値として
(setf eos (cons nil nil))
(read stream nil eos)
など

ファイルを操作sるための組み込み関数

probe-file:ファイルが存在するかどうか調べる

(probe-file "bar.lisp")
bar.lispというファイルがあればnil以外の値を返す.なければnilを返す.

delete-file:存在するファイルを消す

(when (probe-file "bar.lisp")
   (delete-file "bar.lisp"))
bar.lispというファイルを消す.存在しない場合はエラーとなるので,存在することを確かめて呼び出す.

rename-file:ファイル名を変える

(when (probe-file "bar.lisp")
   (rename-file "bar.lisp"))
delete-fileと同様に,ファイルが存在しない場合はエラーとなるため,
存在することを確認してから使う.

1から10までをtest.datに出力する

(with-open-file (out "test.dat" :direction :output)
  (dotimes (x 10) (print x out)))

test.datから読み込み,表示する.

(with-open-file (in "test.dat" :direction :input)
  (let (num)
    (while (setq num (read in nil)) (print num))))

0 
1 
2 
3 
4 
5 
6 
7 
8 
9 
=> nil

11.6 文字列に対する入出力

ストリームの中には,文字列への出力ストリーム(string-output-stream)と文字列からの入力ストリーム(string-input-stream)がある.

with-input-from-string

with-open-fileに似ている.
(with-input-from-string (変数 文字列)
   式1 ... 式n)
とすると,式1...式nが評価される間,変数に文字列からの入力ストリームがバインドされる.
(with-input-from-string
    (stream "(a b) (c d)")
  (setq x (read stream))
  (setq y (read stream)))
xには(a b),yには(c d)がバインドされる.
最終更新:2011年10月07日 19:45