I would like to write a file whose first few lines are text and the rest
is binary. Can I do this in Lisp without writing two files and then
concatenating
them?
In particular, I am trying to write a binary .ppm file. Yes, I know I
can
do it all in text but the files get pretty big that way.
Supposing that I can't, can anyone tell me the best way to write a
purely
binary file? I'm thinking that opening the file with :element-type 'bit
and using write-byte should work. Is there a better way?
Any experience or suggestions?
Thanks.
Benji Shults
Dept. of Math
Kenyon College
[Posted and mailed.]
Benjamin Shults <·······@kenyon.edu> wrote:
>I would like to write a file whose first few lines are text and the
>rest is binary. Can I do this in Lisp without writing two files and
>then concatenating them?
Sure. The most general thing to do is to open the file up for
character output, do the test output, and then re-open it for binary
output in :APPEND mode to do the rest:
(let ((pathname (make-pathname :defaults (user-homedir-pathname)
:name "test" :type "xxx"
:version :newest)))
(with-open-file (stream pathname
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(format stream "Hello world~%"))
(with-open-file (stream pathname
:direction :output
:if-exists :append
:element-type '(unsigned-byte 8))
(loop repeat 100 do (write-byte (random 256) stream))))
Note that writing character output that conforms to a particular
standard is tricky: You have to worry about what character coding the
CL system is using and how it handles end-of-line conventions. There
is, unfortunately, no standard way of specifying an :EXTERNAL-FORMAT
of the UNIX convention of 8-bit extended ASCII characters and NL
end-of-lines. The only way of doing this portably is to open the file
in binary mode, convert the characters to ASCII as best you can, and
output them a byte at a time.
--David Gadbois