storing to a file

Glynn Clements
Fri, 15 Nov 2002 00:46:11 +0000

Johan Steunenberg wrote:

> thanks for your advice, I guess it sweetens the situation, though I
> really would like to know how to store in a binary format.

Here's one possibility, using the Storable class:

import Word
import IOExts
import Foreign.Ptr
import Foreign.Storable
import Foreign.Marshal.Alloc

toOctets :: Storable a => a -> [Word8]
toOctets x = unsafePerformIO $ do
    ptr <- malloc :: Storable a => IO (Ptr a)
    poke ptr value
    let bptr = castPtr ptr :: Ptr Word8
    bytes <- mapM (peekElemOff bptr) [0 .. sizeOf x - 1] :: IO [Word8]
    free ptr
    return bytes

However, this will use the internal format, which will vary between
architectures, so a file written on one architecture may not work on a
different architecture.