0
votes

I am writing a simple program. The program has 2 QStrings set with following variables: path and name of file, there is a 3rd QString which I later on use to put the result of the append of the first 2 QString together in. What I want to do is append the 2 QStrings and put them in the appendAll QString, and then send the appendAll QString to the QFile variable constructor. Now when I do that, it prints "Failed to Create File", this is the code I used:

#include <QString>
#include <QTextStream>
#include <QFile>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);


    QTextStream output(stdout);

    QString location = "/home/mahmoud/Destkop";
    QString name = "mahmoud.txt";
    QString appendAll;

    if( !location.endsWith("/") )
    {
        location.append("/");
    }

    appendAll = location.append(name);

    output << appendAll << endl;

    QFile myFile(appendAll);

    if(myFile.open(QIODevice::WriteOnly | QIODevice::Text ))
    {
        output << "File Has Been Created" << endl;
    }
    else
    {
        output << "Failed to Create File" << endl;
    }

    QTextStream writeToFile(&myFile);

    writeToFile << "Hello World" << endl;

    myFile.close();

    return a.exec();
}

But when I type the string directly into the QFile variable constructor in the same program it prints, "File Has Been Created" and I find it on my desktop, the below code works fine:

QFile myFile("/home/mahmoud/Desktop/mahmoud.txt");

if(myFile.open(QIODevice::WriteOnly | QIODevice::Text ))
{
    output << "File Has Been Created" << endl;
}
else
{
    output << "Failed to Create File" << endl;
}

I want to be able to already have QStrings and append them and send them to the QFile variable constructor, any suggestions on how to solve my problem? Thank You

2
I think there's an error in your first code snippet: "/home/mahmoud/Destkop" should probably be "/home/mahmoud/Desktop".user2448027

2 Answers

1
votes

There is typing error in your code: Destkop should be Desktop. Qt can't create file in non-existent directory.

7
votes

Do not hard-code this filesystem location. Instead, in Qt4 you should be using QDesktopServices:

QString location = 
    QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);

In Qt5, it's QStandardPaths:

QString location = 
    QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);

This is important because /home/username/Desktop is not guaranteed to be the user's Desktop folder.