Read the contents of a file, then append to the file
I cannot figure out how to read the contents of a file and then append more data to a file. hGetContents
, which I am using at the moment seems to close the file after read开发者_如何学运维ing, thus I cannot write to it.
How can I work around this?
Maybe something like:
import System.IO
modifyFile :: FilePath -> (String -> String) -> IO ()
modifyFile fn func = do
str <- readFile fn
length str `seq` return ()
appendFile fn (func str)
The seq call forces the file to be fully read and the file closed before we reopen to append to it (or the write fails).
This is quick and dirty. You might look into System.IO.hSeek and related functions if you want to do something more elaborate. E.g. open it, read it, seek to the end, append.
You shouldn't get the contents of the file.
The appropriate thing to do is to open file, edit and close. The getContent method, gets the content for you and does nothing else.
Pseudo Code ::
Open File
Read/Append File (as the case may be)
Close the file
Here's the doc http://haskell.org/ghc/docs/latest/html/libraries/base/System-IO.html
You are correct that hGetContents
closes (or rather, semi-closes) a file handle so you cannot use it for other operations anymore. One option is to acquire a new handle for the file after reading it and then using that for appending, but this might work in unexpected ways if, for some reason, you don't process the file contents completely before re-opening it.
Another way is to open the file in ReadWriteMode
and to read the contents in some other way, for example, using hGetLine
(if your data is line based) until you reach the end-of-file and then appending using the same handle.
精彩评论