Reading an int sequence from a binary file

I have a binary file containing a sequence of 32 bit ints. How do I start reading them into a list (or Data.Array, which I will probably use)?

All I can find in the documentation is the hGetBuf function, and it is unclear how to use it (does Ptr need a buffer?). http://www.haskell.org/ghc/docs/latest/html/libraries/base-4.3.1.0/System-IO.html#v:hGetBuf

Of course, there should be a simple approach, but I can not find it!

+6
source share
2 answers

If the file is only 32-bit ints, then heed the @TomMD warning. Something like this should do the job.

import Control.Applicative import Control.Monad import Data.Binary import Data.Binary.Get import Data.Binary.Put import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString as BS import Data.Int import System.Posix testPut = BL.writeFile "foo.bin" . runPut . mapM_ put $ nums where nums :: [Int32] nums = [5,6,7,8] testGet :: IO [Int32] testGet = do n <- fromInteger . toInteger . fileSize <$> getFileStatus "foo.bin" let readInts = runGet (replicateM (n `div` 4) get) readInts . BL.fromChunks . (:[]) <$> BS.readFile "foo.bin" 
+4
source

You can do this quite easily with the binary package. You can find the documentation for reading files here .

It already includes a way to deserialize a list of 32-bit integers, so you just need to call the decodeFile function. For clarity, you can have a typical version:

 decodeIntsFile :: FilePath -> IO [Int32] decodeIntsFile = decodeFile 

Then, if you want your list of integers to be an array, use the appropriate array transformation, for example listArray .

+4
source

Source: https://habr.com/ru/post/890136/


All Articles