In Haskell, I want to read a file and then write to it. Do I need strictness annotation?

后端 未结 4 1330
予麋鹿
予麋鹿 2021-02-07 09:14

Still quite new to Haskell..

I want to read the contents of a file, do something with it possibly involving IO (using putStrLn for now) and then write new contents to th

4条回答
  •  不要未来只要你来
    2021-02-07 09:32

    You can duplicate the file Handle, do lazy write with original one (to the end of file) and lazy read with another. So no strictness annotation involved in case of appending to file.

    import System.IO
    import GHC.IO.Handle
    
    main :: IO ()
    main = do
        h <- openFile "filename" ReadWriteMode
        h2 <- hDuplicate h
    
        hSeek h2 AbsoluteSeek 0
        originalFileContents <- hGetContents h2
        putStrLn originalFileContents
    
        hSeek h SeekFromEnd 0
        hPutStrLn h $ concatMap ("{new_contents}" ++) (lines originalFileContents)
    
        hClose h2
        hClose h
    

    The hDuplicate function is provided by GHC.IO.Handle module.

    Returns a duplicate of the original handle, with its own buffer. The two Handles will share a file pointer, however. The original handle's buffer is flushed, including discarding any input data, before the handle is duplicated.

    With hSeek you can set position of the handle before reading or writing.

    But I'm not sure how reliable would be using "AbsoluteSeek 0" instead of "SeekFromEnd 0" for writing, i.e. overwriting contents. Generally I would suggest to write to a temporary file first, for example using openTempFile (from System.IO), and then replace original.

提交回复
热议问题