1

Trying to read a binary file of Word8, I have the following program:

import qualified Data.Binary as B
type Chars = [B.Word8]

printChars :: Chars -> IO()
printChars cs = mapM_ print cs

main :: IO()
main = do
  chars <- B.decodeFile "chars"
  printChars chars

When I run it, I get an error:

$ ./test
test: too few bytes. Failed reading at byte position 241

It seems decodeFile expects an infinite list. How can I tell it to just read as many elements as possible?

Edit:

Here was the code I was looking for: (This works with any type, not just Word8.)

import Prelude hiding ( readFile )
import Data.ByteString.Lazy ( readFile )
import Data.Binary.Get ( isEmpty, runGet )
import qualified Data.Binary as B

type Chars = [B.Word8]

printChars :: Chars -> IO()
printChars cs = mapM_ print cs

-- see http://hackage.haskell.org/package/binary-0.7.1.0/docs/Data-Binary-Get.html
-- function getTrades
getChars = do
  e <- isEmpty
  if e then return []
  else do
    c <- B.get
    cs <- getChars
    return (c:cs)

main :: IO()
main = do
  input <- readFile "chars"
  printChars $ runGet getChars input

1 Answer 1

4

Data.Binary is used to serialize known types in a canonical way (defined by the Binary class instance). In general it isn't intended for unstructured data.

In the case you gave us, you are attempting to deserialize the bytes in a file to an object of type [B.Word8]. If you look in the Data.Binary source code, you can see the following

instance Binary a => Binary [a] where
    get    = do n <- get :: Get Int
            getMany n

which basically means that arrays are stored as follows

[length of array, val1, val2, ....]

so, when you applied the value to the file, it read the first Int in the file (no doubt, a very large number), then attempted to read that number of values.

If you just want to load the file as bytes, you should use Data.ByteString.getContents

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.