arnesi

Utilites for file system I/O 

(defmacro with-input-from-file ((stream-name file-name &rest args) &body body)
  "Evaluate @var{body} with @var{stream-name} bound to an
  input-stream from file @var{file-name}. @var{args} is passed[...]
  directly to @code{OPEN}."
  (when (member :direction args)
    (error "Can't specifiy :DIRECTION in WITH-INPUT-FILE."))
  `(with-open-file (,stream-name ,file-name :direction :input ,@args)
     ,@body))
(defmacro with-output-to-file ((stream-name file-name &rest args) &body body)
  "Evaluate @var{body} with @var{stream-name} to an output stream
  on the file named @var{file-name}. @var{args} is sent as is to[...]
  the call te @var{OPEN}."
  (when (member :direction args)
    (error "Can't specifiy :DIRECTION in WITH-OUTPUT-FILE."))
  `(with-open-file (,stream-name ,file-name :direction :output ,@args)
     ,@body))
(defun read-string-from-file (pathname &key (buffer-size 4096) (element-type 'character))
  "Return the contents of @var{pathname} as a string."
  (with-input-from-file (file-stream pathname)[...]
    (with-output-to-string (datum) 
      (let ((buffer (make-array buffer-size :element-type element-type)))
	(loop for bytes-read = (read-sequence buffer file-stream)
	      do (write-sequence buffer datum :start 0 :end bytes-read)
	      while (= bytes-read buffer-size))))))
(defun write-string-to-file (string pathname &key (if-exists :error))
  "Write @var{string} to @var{pathname}."
  (with-output-to-file (file-stream pathname :if-exists if-exists)
    (write-sequence string file-stream)))
(defun copy-file (from to &key (if-to-exists :supersede))
  (with-input-from-file (input from :element-type '(unsigned-byte 8))
    (with-output-to-file (output to :element-type '(unsigned-byte 8)[...]
				    :if-exists if-to-exists)
      (loop
	 with buffer-size = 4096
	 with buffer = (make-array buffer-size :element-type '(unsigned-byte 8))
	 for bytes-read = (read-sequence buffer input)
	 while (= bytes-read buffer-size)
	   do (write-sequence buffer output)
	 finally (write-sequence buffer output :start 0 :end bytes-read)))))