Error reading and writing the same file at the same time in Haskell

I need to change the file in place. Therefore, I planned to read the contents of the file, process it, and then write the output to the same file:

main = do input <- readFile "file.txt" let output = (map toUpper input) -- putStrLn $ show $ length output writeFile "file.txt" output 

But the problem is that it works as expected only if I uncomment the 4th line - where I just print the number of characters for the console. If I do not uncomment it, I get

 openFile: resource busy (file is locked) 

Is there a way to force the reading of this file?

+4
source share
1 answer

The simplest thing could be strict ByteString IO:

 import qualified Data.ByteString.Char8 as B main = do input <- B.readFile "file.txt" B.writeFile "file.txt" $ B.map toUpper input 

As you can see, this is the same code, but with some features replaced by ByteString versions.

Lazy io

The problem you are facing is that some Haskell IO features use "Lazy IO", which has amazing semantics. In almost every program, I would avoid lazy I / O.

These days, people are looking for replacements for Lazy IOs such as Conduit and the like, and lazy IO is seen as an ugly hack that, unfortunately, is stuck in the standard library.

+5
source

Source: https://habr.com/ru/post/1442442/


All Articles