c++qtqfileqt-resource

QFile::copy unable to copy a file from the resource system


QFile::copy won't copy file from my resources. My code is:

QTemporaryFile file;
file.setFileTemplate("/tmp/XXXXXX.wav");
file.open();

qDebug() << QFile::copy(":/busy.wav", file.fileName());

Displays "False". But if I set destination name manually, say for example:

qDebug() << QFile::copy(":/busy.wav", "blabla.wav");

Or:

qDebug() << QFile::copy(":/busy.wav", file.fileName() + ".wav");

It works fine then. What is wrong with this copy or with my code?


Solution

  • That is simply because QFile does not overwrite existing files (from the documentation):

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

    The most simple solution would be to make a dedicated function to create tmp filenames. Since QTemporaryFile deletes the file when destroyed, this will work fine:

    QString generateName()
    {
        QTemporaryFile file;
        file.setFileTemplate("/tmp/XXXXXX.wav");
        file.open();//QTemporaryFile creates the file. QFile::copy will not be able to overwrite it, so you will need to delete it first.
        file.close();
        return file.fileName();
    }//QTemporaryFile gets destroyed, and deletes the file. Now QFile::copy will work fine.
    
    int main()
    {
        QFile::copy(your_resource_file, generateName());
    }