Ein
Ein

Reputation: 1603

Haskell: Clear file contents using an open handle

In Haskell, how can one clear a file's contents when you already have an open file handle and do not wish to close it? Is there some easy way that isn't apparent to me from the System.IO API?

In a less restrictive situation, the easiest way to clear a file's contents is with writeFile awesomefile.txt "". If you already have an open file handle to awesomefile.txt though, then writeFile will fail with an exception (namely "openFile: resource busy (file is locked)").

I thought perhaps using hSeek to set the handle back to the start position might have a similiar effect, but it doesn't. After seeking the handle back to the start, the next hPutStr call will just overwrite as many bytes as necessary (which makes more logical sense anyway).

The situation comes up in my program where I want to very frequently write information to a file for logging purposes. Only the most recent log data is relevant (and gigantic files are very inconvenient), so the file is emptied before each write. Because writes are so frequent, I would like to only open the file handle once.

only related question:
Clear file contents in haskell language

Upvotes: 2

Views: 275

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 152867

You can use hSetFileSize to truncate a file to a given size.

Upvotes: 5

Related Questions