从二进制文件中读取整数序列

oad*_*ams 6 file-io haskell

我有一个包含32位整数序列的二进制文件.我如何将它们读入列表(或Data.Array,我可能最终会使用它)?

我在文档中找到的就是这个hGetBuf函数,目前还不清楚如何使用它(需要Ptr到缓冲区?).http://www.haskell.org/ghc/docs/latest/html/libraries/base-4.3.1.0/System-IO.html#v:hGetBuf

当然必须有一个简单的方法,但我找不到它!

Ant*_*ony 4

如果文件只是 32 位整数,那么请注意 @TomMD 的警告。像这样的东西应该可以完成工作。

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"
Run Code Online (Sandbox Code Playgroud)