problems with working with Handles

Niels Reyngoud nreijngo@cs.uu.nl
Fri, 13 Jun 2003 10:33:31 +0200


Hello all,

Thanks for your replies on our previous posts. To avoid the lazy 
behaviour, we tried to write our own IO module "IOExts2" which basically 
redifnes
readFile, writeFile and appendFile to make sure they use binary-mode and 
strict behaviour. The libary is as follows:

----------
module IOExts2(readFile', writeFile', appendFile') where

import IO
import IOExts

readFile' :: String -> IO String
readFile' inputfile = do readhandle <- openFileEx inputfile (BinaryMode 
ReadMode)
             x <- hGetContents readhandle
             seq x (return x)
       {-      seq x (do hClose readhandle
                       return x) -}
             

writeFile' :: String -> String -> IO()
writeFile' outputfile text = seq text (writeFile'' outputfile text)

writeFile'' :: String -> String -> IO()
writeFile'' outputfile text = do writehandle <- openFileEx outputfile 
(BinaryMode WriteMode)
                                 hPutStr writehandle text
                      hFlush writehandle
                        hClose writehandle

appendFile' :: String -> String -> IO()
appendFile' outputfile text = seq text (appendFile'' outputfile text)

appendFile'' :: String -> String -> IO()
appendFile'' outputfile text = do appendhandle <- openFileEx outputfile 
(BinaryMode AppendMode)
                                  hPutStr appendhandle text
                      hFlush appendhandle
                      hClose appendhandle

---------------

Yet, there's still one problem left with readFile'. The handles of 
appendFile' and writeFile' are properly closed, but when I try to close 
the handle used for reading (as shown by the parts
commented above) and try the following small test, which uses a file 
"123.txt"  that consists of the string "blaat" only a "b" is outputted. 
When  I do not close the handle, the entire string "blaat" is outputted.

test = do x <- readFile' "123.txt"
              putStr x

Regards,
Niels Reyngoud