[Solved] Overwriting files when copying using QFile



  • Here's a code snippet that works fine provided the destinationFile doesn't exist:
    @
    QFile destinationFile, sourceFile;
    QDir destination("../CopiedFiles");
    QString fileName("MyData.dat");
    destinationFile.setFileName(destination.filePath(fileName));
    sourceFile.setFileName("../MainData/" + fileName);
    sourceFile.copy(destinationFile.fileName());
    @
    Is there any way to overwrite the file automatically, or would I have to go the long way around (checking if the destinationFile exists, and if it does, removing it and then copying)?



  • As the docs say, QFile::copy() will not overwrite an existing file. It's hardly a "long way around" to delete or rename the file first.

    @
    if ( !destinationFile.exists() || destinationFile.remove() ) {
    if ( !sourceFile.copy(destinationFile.fileName()) )
    // Could not copy file
    }
    else
    // Could not remove file
    @



  • But "Remove, Copy" is hardly atomic, how do I ensure other processes, such as the web server never fail to find the file?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.