Binary IO

Iavor Diatchki iavor.diatchki at
Fri Apr 22 17:37:07 EDT 2005

I am just going to summarize what we are proposing so far:
> hGetByte :: Handle -> IO Word8
> hPutByte :: Handle -> Word8 -> IO ()
I like the "byte" terminology even though it may not be absolutely accurate.

Simon suggested that these should only work on handles that are in
binary mode, and that seems reasonable to me.  Other people would like
them to work on files open in text mode.  I am not sure why we need
that, text mode suggests that we want to think of the file as
containing characters and not bytes (and should ideally support
different character encodings etc).  If a programmer needs to muck
around with the raw bytes in a "text" file they can always implement
that on top of the binary file interface.
I also don't think that '\n' should flush buffers in binary mode --- I
would like a binary file to simply contain bytes.  I don't think that
line buffering makes sense in that situation, but perhaps treating
line buffering as block buffering is reasonable (i.e. lines are as big
as the buffer).

There was also a request for operations that get multiple bytes:
> readBinaryFile :: FilePath -> IO [Word8]
> writeBinaryFile :: FilePat -> [Word8] -> IO ()

I think something like that might be useful, but I would prefer if
they were using handles, and arrays, e.g. something like:
> hGetBytes :: Handle -> Int -> IO (UArray Int Word8)
> hPutBytes :: Handle -> UArray Int Word8 -> IO ()
With the current interface we can kind of implemenet something like
this using hGetArray, and unsafeFreeze, but it would be nicer to not
have to use the unsafe freeze.  The 'int' argument for the first
function says how many bytes to read.  Using these it seems easy to
implement readBinaryFile and writeBinaryFile.


More information about the Libraries mailing list