読者です 読者をやめる 読者になる 読者になる

ファイル読込み関数

common lisp utility

テキストおよびバイナリファイル読込み関数定義。

(defun read-binary-file (path)
  (with-open-file (in path :element-type '(unsigned-byte 8))
    (let ((as (make-array (file-length in) :element-type '(unsigned-byte 8))))
      (read-sequence as in)
      as)))

(defun read-file (path)
  #+SBCL (sb-ext:octets-to-string (read-binary-file path))
  #-SBCL (with-output-to-string (out)
           (with-open-file (in path)
             (let ((io (make-echo-stream in out)))
               (unwind-protect
                   (loop while (read-line io nil nil))
                 (close io))))))


使用例。

> (read-file ".profile")
--> "# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.
# see /usr/share/doc/bash/examples/startup-files for examples.
# the files are located in the bash-doc package.

# the default umask is set in /etc/profile
#umask 022 ...以下略..."

> (read-binary-file ".profile")
-->#(35 32 126 47 46 112 114 111 102 105 108 101 58 32 101 120 101 99 117 116 101
  100 32 98 121 32 116 104 101 32 99 111 109 109 97 110 100 32 105 110 116 101
  114 112 114 101 116 101 114 32 102 111 114 32 108 111 103 105 110 32 115 104
  101 108 108 115 46 10 35 32 84 104 105 115 32 102 105 108 101 32 105 115 32
  110 111 116 32 114 101 97 100 32 98 121 32 98 97 115 104 40 49 41 44 32 105 #|...以下略...|#)