Search code examples
c++qtqfileqdir

QT - copying a file to AppData


My program prompts the user to select a file to process. My program processes it and it tries to save the file to AppData.

This is how I do it:

QSettings settings(QSettings::IniFormat, QSettings::UserScope, "FlameTool", "FlameTool");
addin_path = QFileInfo(settings.fileName()).absolutePath() + "/addins/" + id + ".limod" ;
qDebug(addin_path.toLocal8Bit());

if(QFile::copy(QDir::toNativeSeparators(file_passed),QDir::toNativeSeparators(addin_path)))
    qDebug("copied");
else
    qDebug("not copied");

Everytime this part of code is executed, it outputs "not copied". How can I copy the file?


Solution

  • In order to do what you want, I would like to advice using QStandardPaths class instead:

    Set the application name in, for example, main.cpp

    int main(...)
    {
        [..]
        a.setApplicationName("FlameTool");
    }
    

    Copy the file:

    QString addin_path = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    QDir dir(addin_path);
    if (!dir.exists())
        dir.mkpath(addin_path);
    if (!dir.exists("addins"))
        dir.mkdir("addins");
    
    dir.cd("addins");
    addin_path = dir.absoluteFilePath(id + ".limod");
    if (QFile::exists(addin_path))
        QFile::remove(addin_path);
    
    if(QFile::copy(file_passed, addin_path))
        qDebug("copied");
    else
        qDebug("not copied");
    

    Please also note that:

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