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