On 2020-11-04, R.Wieser <add...@not.available> wrote:
> Charlie,
>
>> How about just checking whether the names of the
>> source and target files are the same?
>
> Yeah, that passed my find too ...
<snip>
>> Warning: do _not_ attempt to simply delete the target file
>> and rename the work file as the target file;
>
> :-) Rename the targetfile to temp, rename the workfile to target file,
> delete the temp file - and only if no errors pop up anywhere in between.
That's getting complicated, which is why I just copy the work file back.
In addition, it works even if the two file names come out the same by any
syntactical trick, in which case you effectively update the file in place.
In fact, I honed the technique developing routines to do just that.
Just to provide a bit of background, I discovered that the reason the
delete/rename technique sometimes fails is that when you tell Windows
to delete a file, it doesn't necessarily do it right away, but queues
the request and does it whenever it feels like getting around to it.
So your program thinks the file is gone, but it might not be yet.
If this happens, a subsequent rename might fail because the original
file is still there.
The odds of this happening aren't that great - well within Microsoft's
"sort of works, most of the time" reliability criteria. But I've written
programs that are running every day in about a thousand customer sites;
in such an environment, a failure rate of even 0.01% results in enough
anguished telephone calls to make the support people unhappy (in addition
to the customers themselves, of course).
This problem is unique to Windows; delete/rename is bombproof under Linux
(although I can think of some unlikely situations which might create a
race condition that will cause a failure under any OS).