2

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?

movildima
  • 37
  • 1
  • 9
  • Debug tip: When a function fails, check actual argument values passed to it. Sure way to get real values is to put them to temp variables (if not already in variable), pass those as arguments, and set breakpoint at call line, or just print them. – hyde Mar 11 '14 at 16:39
  • Qt tip: you do not need `toNativeSeparators` with Qt functions. – hyde Mar 11 '14 at 16:41

2 Answers2

5

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).

movildima
  • 37
  • 1
  • 9
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • Okay, with some adoptions to the code, using QStandardLocations instead of QDesktopServices, and it works! The thing is, I need it to write to AppData\Roaming\, not to AppData\Local\ . Is there a way to locate Roaming folder? – movildima Mar 11 '14 at 20:11
  • Well, I'll tick this as answer, because it really helped me. – movildima Mar 12 '14 at 20:12
1

Firstly, you should remove any existing (because it will prevent copying as QFile::copy does not overwrite any existing file) file and warn if not possible to remove. Secondly you should validate the destination path.

user2672165
  • 2,986
  • 19
  • 27