Read and writing to file in Haskell -


i trying read contents of file, turn text upper-case , write back.

here code had written:

import system.io import data.char  main =     handle <- openfile "file.txt" readwritemode     contents <- hgetcontents handle     hclose handle     writefile "file.txt" (map toupper contents)     return () 

however, writes nothing file, in fact, clears it.

i made changes:

main =     handle <- openfile "file.txt" readwritemode     contents <- hgetcontents handle     writefile "file.txt" (map toupper contents)     hclose handle     return () 

however, error resource busy (file locked). how can working , why didn't work in both cases?

i think problem hgetcontents lazy. contents of file not read in when use hgetcontents. read in when needed.

in first example open file , want contents, close file before them. write file. when write existing file contents cleared, since closed file no longer have access file contents.

in second example open file , try write file, because contents not read until needed (when transformed , written back) end trying write , read same file @ same time.

you write file named file2.txt when done, delete file.txt , rename file2.txt file.txt


Comments