Haskell ReadWriteMode 文件句柄

Haskell ReadWriteMode file handle

在阅读Learn You A Haskell时,我发现你可以使用ReadWriteMode作为第三个参数来openFile.

但这应该处理文件的写入和读取吗? 我做了一些测试:

import System.IO

main = do
    handle   <- openFile "myfile" ReadWriteMode
    contents <- hGetContents handle
    putStrLn contents
    hPutStr handle "Something"
    hClose handle

然而,这返回了一个错误:

*** Exception: myfile: hPutStr: illegal operation (handle is closed)

那么,ReadWriteMode 的意义何在?我正在寻找任何可以使用它的真实案例。

这似乎有效。

import System.IO
import qualified System.IO.Strict as SIO
import GHC.IO.Handle

slurp h = do
  h' <- hDuplicate h
  hSeek h' AbsoluteSeek 0
  SIO.hGetContents h'

main = do
    handle   <- openFile "myfile" ReadWriteMode
    contents <- slurp handle
    putStrLn contents
    offset <- hTell handle
    putStrLn $ "handle position: " ++ show offset
    hPutStrLn handle "Something new"
    hClose handle

System.IO.Strict 来自 strict package

编辑:您甚至可能不需要使用 SIO.hGetContents - 简单的 hGetContents 似乎也有效。