[Haskell-cafe] openBinaryFile

Jules Bean jules at jellybean.co.uk
Tue May 15 11:27:18 EDT 2007


Eric wrote:
> Hello all,
>
> Does anyone have some sample code for reading and writing to binary 
> files?


openBinaryFile is a bit of a red herring. All it does is disable the 
line-ending interpretation which may or may not happen on some OSes when 
you open a file in text mode.

For simple binary access to a file, just use hGetChar and friends. 
hGetChar is quite badly named (and typed) it is really hGetByte and it 
should really have type IO Word8. You can build up reading a few words 
at a time like this:

hGetN :: Int -> Handle -> IO [Word8]
hGetN n h = replicateM n (fmap (fromIntegral.fromEnum) (hGetChar h)) 


...and so on. I wrote a naive binary file library for a simple binary 
format using this method, and it works fine.

If you start to care about performance, you can use the Word8 versions 
of Data.Bytestring, which store the data more efficiently in memory and 
load it from the file more efficiently. You also benefit from a slightly 
cleaner API in a few of the corner cases.

If you want a higher-level API over binary file access then Data.Binary 
is for you, but beware:

Data.Binary is really two libraries. One part of it is for serialisation 
of haskell types to and from binary structures (you haven't said that is 
what you want, but maybe it is). However the other part is an 
abstraction over reading/writing binary files at all. That part is more 
closely related to your question.

Jules



More information about the Haskell-Cafe mailing list