Copy file even when destination exists (in Qt)

sashoalm picture sashoalm · Feb 18, 2013 · Viewed 19.5k times · Source

In the QFile::copy documentation it says

If a file with the name newName already exists, copy() returns false (i.e., QFile will not overwrite it).

But I need to copy a file even if the destination exists. Any workaround available in Qt for that?

Deleting the file is the obvious solution but it invites a race condition...

Answer

karlphillip picture karlphillip · Feb 18, 2013
if (QFile::exists("/home/user/dst.txt"))
{
    QFile::remove("/home/user/dst.txt");
}

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