[Haskell-cafe] Strange behaviour with writeFile
Donald Bruce Stewart
dons at cse.unsw.edu.au
Sun Feb 4 18:24:25 EST 2007
cmb21:
> fo/haskell-cafe>,
> <mailto:haskell-cafe-request at haskell.org?subject=subscribe>
> Errors-To: haskell-cafe-bounces at haskell.org
> Status: O
> Content-Length: 778
> Lines: 27
>
> Hi,
>
> I am observing some rather strange behaviour with writeFile.
>
> Say I have the following code:
>
> answer <- AbstractIO.readFile "filename"
> let (answer2, remainder) = parseAnswer answer
> if remainder == "" && answer2 == ""
> then do
> AbstractIO.putStrLn $ "completed"
> else do
> AbstractIO.putStrLn answer2
> AbstractIO.writeFile "filename" remainder
>
> With the above I get an error saying the resources to "filename" are
> locked. If I add the line "AbstractIO.putStrLn $ show (answer2, remainder)
> before I call writeFile it suddenly magically works!
lazy IO at play. One quick fix would be to use strict IO:
import qualified Data.ByteString.Char8 as S
import Data.ByteString (ByteString)
main = do
ans <- S.readFile "t" -- strict file IO
print (S.length ans) -- current size
let (x,xs) = S.splitAt 10 ans -- "parse"
S.writeFile "t" xs
ans' <- S.readFile "t"
print (S.length ans') -- new size
$ time ./a.out
2487212
2487202
This comes up often enough that I think we should have a strict readFile for Strings
-- Don
More information about the Haskell-Cafe
mailing list