[Haskell-cafe] problem with IO, strictness, and "let"

Stefan O'Rear stefanor at cox.net
Fri Jul 13 15:08:39 EDT 2007


On Fri, Jul 13, 2007 at 07:59:22PM +0100, Andrew Coppin wrote:
> Stefan O'Rear wrote:
>> The problem is that you're closing the file twice.  When you call any
>> function of the getContents family, you assign to that function the
>> responsibility to close the file, no sooner than it is no longer needed.
>> Don't call hClose yourself, Bad Things will happen.
>>   
>
> Care to elaborate on "bad things"? (I.e., will this just crash the program 
> with an error, or will it do something more serious?) I must admit, I 
> thought closing such a file was simply no-op.

If you close the file, the stream will suddenly end.  I believe silent
data corruption is worse than a crash :)  (currently, hGetContents also
truncates on I/O error, but that's much less common and syslog will tell
you about it anyway)

> I can't remember why exactly, but somewhere or other I wrote some code that 
> does this. (Basically I want to shut the file without reading all of it, so 
> I can reopen it and start reading from the beginning again.) Is there a 
> sane way to do this? Or am I going to have to start playing with explicit 
> reads and writes? (Obviously I could just hang on to *all* of the input 
> stream returned from getContents - but that could be quite large. The 
> current way gives me low memory usage...)

Did you actually try it?  getContents is *lazy*.  it doesn't read any
more of the file than it has to.  If it read the whole file immediately,
you obviously DO need the whole file.

This is also why closing a file after getContentsing it is Bad -
getContents can't keep reading after you've closed the handle.

Stefan
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070713/c1725a43/attachment.bin


More information about the Haskell-Cafe mailing list