[Haskell - I/O] Problem with 'readFile'
Hi, I use the operation 'readFile' for obtain information locates on a file. When I try to write another information on the same file, I obtain this error message: "openFile: permision denied". I found this: "The readFile operation holds a semi-closed handle on the file until the entire contents of the file have been consumed. It follows that an attempt to write to a file (using writeFile, for example) that was earlier opened by readFile will usually result in failure with isAlreadyInUseError." in this web http://www.haskell.org/onlinereport/io.html. How can I break that semi-closed handle for to write in the preaviously readed file? Thank you.
L. J. wrote:
Hi, I use the operation 'readFile' [...]
How can I break that semi-closed handle for to write in the preaviously readed file? Thank you.
Not at all. But you can get the same effect you get from 'readFile' if you use 'openFile' and 'hGetContents'. If you do the latter, you can really close the semi-closed handle by calling 'hClose'. However, chances are, that you will not have consumed the whole file at the point where you close it (lazy evaluation can^W will be tricky), you will find that you write a new file with empty content, because apparently you read an empty file when in fact it wasn't empty, and so on. In short: don't do that. Also, don't fight the error message, understand, that it saved you from trashing a perfectly good file. Instead, 'readFile' your data, 'writeFile' it into a new(!) file, then 'renameFile' the new over the old one. Before doing anything else, get a deep understanding of lazy IO. (And this understanding will basically be, that a database package (gdbm, Berkeley DB, you name it) will serve you better.) Udo. -- "The greatest dangers to liberty lurk in insidious encroachment by men of zeal, well-meaning but without understanding." -- Brandeis
L. J. wrote:
Hi, I use the operation 'readFile' for obtain information locates on a file. When I try to write another information on the same file, I obtain this error message: "openFile: permision denied". I found this: "The readFile operation holds a semi-closed handle on the file until the entire contents of the file have been consumed. It follows that an attempt to write to a file (using writeFile, for example) that was earlier opened by readFile will usually result in failure with isAlreadyInUseError." in this web http://www.haskell.org/onlinereport/io.html.
How can I break that semi-closed handle for to write in the preaviously readed file? Thank you.
Since readFile reads the file lazily (on demand), you have to make sure that the whole file gets read by completely evaluating the result string. BTW, I think haskell-cafe is the more appropriate forum for questions like these. Cheers Ben
participants (3)
-
Benjamin Franksen -
L. J. -
Udo Stenzel