problems with working with Handles

Keith Wansbrough Keith.Wansbrough@cl.cam.ac.uk
Thu, 12 Jun 2003 17:57:33 +0100


> 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")
> 
> 
> The text which should be in the outputfile is "testit extra extra2", 
> instead "testit extra2" is written in.

The contents of output.txt in the filesystem is undefined until you
close the handle.  And what do you expect to happen with two handles
open on the same file for writing?  Bad things are going to happen...

For your other question, see the previous thread that someone else
mentioned.  hGetContents is a bit badly behaved, and should only be
used in trivial cases.  Here you should use hGetLine or hGetChar
instead.  That way you know where you are in the file, and calling
hClose is safe.

--KW 8-)