LoginSignup
11
11

More than 5 years have passed since last update.

ファイル全体を読み込む

Last updated at Posted at 2013-01-03

ファイル全体を読み込んで内容を文字列やバイトベクタで得たい場合、ファイルと同じ大きさの配列を作ってread-sequenceで書き込むのが一般的です。

;; ファイルを読み込んで内容を文字列で返す
(with-open-file (s "abc.txt" :direction :input)
  (let ((buf (make-string (file-length s))))
    (read-sequence buf s)
    buf))

;; ファイルを読み込んで内容をバイトベクタで返す
(with-open-file (s "abc.txt" :direction :input :element-type '(unsigned-byte 8))
  (let ((buf (make-array (file-length s) :element-type '(unsigned-byte 8))))
    (read-sequence buf s)
    buf))

32ビットの環境で大きなファイルを読み込む場合、array-total-size-limitの制限に引っかかることがあるので注意してください。

また、Alexandriaarnesiといったユーティリティライブラリには、このための関数が用意されています。

;; ファイルを読み込んで内容を文字列で返す
(alexandria:read-file-into-string "abc.txt")
(arnesi:read-string-from-file "abc.txt")

;; ファイルを読み込んで内容をバイトベクタで返す
(alexandria:read-file-into-byte-vector "abc.txt")
11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11