[Haskell-cafe] using an external application

Stuart Cook scook0 at gmail.com
Fri Nov 2 04:47:26 EDT 2007

On 11/2/07, Petr Hoffmann <spy.hunter at email.cz> wrote:
> import System.Cmd
> main = do
>           System.Cmd.system "echo hello >output.txt" -- use the external
> application to create an output file
>           o1 <- readFile "output.txt"
>           System.Cmd.system "echo bye >output.txt" -- the second call to
> the external application
>           o2 <- readFile "output.txt"
>           putStr o1 -- "hello" expected, but "bye" printed
>           return 0
> Can you please give me some hint to solve this problem?
> I'm a beginning haskell developer and I'm still a bit confused
> by the IO monad.

This looks like yet another case of the lazy-I/O goblins.

The "readFile" function uses evil magic to avoid actually performing
any I/O until the contents are actually used.  In your case, I suspect
that by the time "o1" is used -- i.e. in the "putStr" call -- the file
contents have already changed, so the lazy I/O reads the new contents
without complaining.

The solution would be to use a version of "readFile" that works in a
stricter way, by reading the file when it's told to, but I don't have
an implementation handy.


More information about the Haskell-Cafe mailing list