problems with working with Handles

Dean Herington heringto@cs.unc.edu
Thu, 12 Jun 2003 14:57:51 -0400 (EDT)


On Thu, 12 Jun 2003, Niels Reyngoud wrote:

> Hello,
> 
> We're two students from the department of computer science at the 
> University of  Utrecht (the Netherlands), and we're havind some severe 
> difficulties in working
> with file handles in Haskell. Consider for example the following program:
> 
> main = do --let inputfile  = "input.txt" 
>       let inputtext  = "testit"
>       let outputfile = "output.txt"
>       writeFile outputfile ""
>       handle2 <- openFileEx outputfile (BinaryMode WriteMode)
>       hPutStr handle2 (inputtext ++ " extra")
>      
>       handle3      <- openFileEx outputfile (BinaryMode ReadMode)
>       inputtext2   <- hGetContents handle3
>       handle4 <- openFileEx outputfile (BinaryMode WriteMode)
>       hPutStr handle4 (inputtext ++ " extra2")

Did you intend `inputtext2` in the line above?

> The text which should be in the outputfile is "testit extra extra2", 
> instead "testit extra2" is written in.

Also, beware that you're reopening `outputfile` (to `handle4`) before 
actually reading the file into `inputtext2`.  (`hGetContents` reads 
lazily.)  I wouldn't be surprised if this causes `inputtext2` to be "".

Dean