[Haskell] reading binary files

minh thu noteed at gmail.com
Wed Apr 5 14:41:02 EDT 2006

hi all,

two things:
1/ i do something and i'd like to know if it is correct
2/ i propose something about 1/

1/ i want to read some binary file (e.g. targa file format : *.tga).

i do this :

-- first way : via IOUArray
showInfoHeader1 handle = do
    a <- newArray_ (1,8) :: IO (IOUArray Int Word8)
    hGetArray handle a 8
    idLength <- readArray a 1 -- or getElems...
    putStrLn ("id length : " ++ show idLength)
    return ()

-- second way : via c-like array
showInfoHeader2 handle = do
    b <- mallocArray 8 :: IO (Ptr Word8)
    hGetBuf handle b 8
    [idLength] <- peekArray 1 b -- or peakArray 8 b
    putStrLn ("id length : " ++ show idLength)
    free b
    return ()

so, briefly, i have to read some content into some kind of buffer
(IOUArray Int Word8 or Ptr Word8), then get one (or more) elements
from the buffor into a standard haskell variable (is it the correct
word ?) (or list).

in the second case, i also have to free the buffer.

in some case, when the data is more than one Word8 long, i have to
'reconstruct' it, i.e.:

[x1,x2] <- getElems a
let x = fromIntegral x1 + fromIntegral x2 * 256 :: Int

is it the correct way to read binary files ?


2/ haskell is (i heard that once ... :-) a high level language, so it
has (must have) good support for abstraction...

but in 1/, i have to choose between different kind of array
representation (and i dont know which one is better) and it seems to
me that the resulting code (compiled) would have to be the same.

the thing i want to say here is : what i want to do is pretty obvious
(in both code) but could be expressed more succintly and with only one
possible syntax:

for example, the couples (hGet*,peek/readArray) could be written in one line;
also, one line for the reading/reconstructing more-than-one-Word8 value.

is it already possible ?
would it be interesting to add such capabilities to haskell ? (i think so)
i can try to add it but i need some pointers about how to do it.

thx a lot,
vo minh thu

More information about the Haskell mailing list