[Haskell-beginners] File I/O: reading from, writing to, same file in one function

Geoffrey Bays charioteer7 at gmail.com
Thu Feb 5 19:51:52 UTC 2015


Question:

As I work my way through Learn You as Haskell, I have been writing small
File IO programs.
Unlike the example in that book, where the author reads from one file,
writes altered data to a temp file and then deletes the original file and
renames the temp file, I have been trying to read from a given file, alter
the data and then overwrite the same file with the new data. Is this
possible?

In a main  do block I have tried:

contents <- readFile fileName

-- do stuff to contents--

writeFile fileName result

After using appendFile to add items to the file, when I call the function
to read and write I get this error:
openFile: resource busy, (file is locked)

I have also tried using the file handles like so:

    handle <- openFile fileName ReadWriteMode
    contents <- hGetContents handle
 -- do stuff to contents --

    hPutStr handle  results
   hClose handle

I have also tried opening with one handle to read, closing it, then using
another handle for writing,
but the error message is that the handle to the file is closed.

I am thinking that the the author of LYAH maybe has good reasons to use a
temp file, or is there another way that is not too difficult to grasp??

Many thanks,

Geoffrey
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20150205/e090e7d8/attachment.html>


More information about the Beginners mailing list