Read and Write to Same File

Glynn Clements glynn.clements at virgin.net
Sun Oct 5 10:59:23 EDT 2003


kuq32tr02 at sneakemail.com wrote:

> I am writing a program that reads and writes to the same file. I was
> having some problems with it writing to the file before it read it. I
> solved it in the following two ways:
> 
> 1.
> main = do text <- readFile "test"
>           let something = somefunc text
>           writeFile "test2" something
>           renameFile "test2" "test"
> 
> 2.
> main = do text <- readFile "test"
>           let something = somefunc text
>           writeFile "test" $! something
> 
> Are both of these correct (guaranteed to give the behavior I want)? 
> Which is better (and why)?

The two versions have substantially different behaviour. E.g.:

1. If there were any additional hard links to "test", version 1 would
result in those links referring to the original file, which would
continue to exist alongside the new file.

2. If another process was concurrently reading "test", version 1 would
result in the process reading the original data, while version 2 would
result in it reading the modified data.

3. If you didn't have write permission for "test", version 2 would
fail, while version 1 would succeed so long as you had write
permission on the directory.

4. With version 1, the new version of "test" would have its ownership
and permissions determined by the usual mechanism for creating new
files; typically, the owner would be determined by the process' UID,
the group would be determined by either the process' GID or the group
of the containing directory (BSD vs SysV behaviour), and have its
permissions determined by the process' umask. With version 2, the
ownership and permissions would remain unchanged.

Replacing a file and overwriting a file are substantially different
operations. In general, neither is necessarily more "correct" than the
other, although specific contexts may favour one over the other.

-- 
Glynn Clements <glynn.clements at virgin.net>


More information about the Haskell-Cafe mailing list