Copy file even when destination exists (in Qt)

The obvious solution is of course to delete the file if it exists, before doing the copy.

Note however that doing so opens up the code to a classic race condition, since on a typical multitasking operating system a different process could re-create the file between your applications' delete and copy calls. That would cause the copy to still fail, so you need to be prepared (and perhaps re-try the delete, but that might introduce a need for count so you don't spend forever attempting, and on and on).


if (QFile::exists("/home/user/dst.txt"))
{
    QFile::remove("/home/user/dst.txt");
}

QFile::copy("/home/user/src.txt", "/home/user/dst.txt");

The simplest retrying I can think of is:

while !QFile::copy("/home/user/src.txt", "/home/user/dst.txt")
{
    QFile::remove("/home/user/dst.txt");
}

But this still isn't a real solution as some of the race conditions are things that don't block remove.

I'm currently hunting for a way to handle writing a web page as an output but without the auto refresh ever catching between the remove and the copy.