C++ – Copy file even when destination exists (in Qt)

cfile-copyingqt

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…

Best Answer

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

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