QFile不会创建该文件

Mah*_*man 0 qt

我正在写一个简单的程序.该程序有2个QStrings设置有以下变量:文件的路径和名称,有一个第三个QString,我稍后用它来将前2个QString的追加结果放在一起.我想做的是附加2 QStrings并将它们放在appendAll QString中,然后将appendAll QString发送到QFile变量构造函数.现在,当我这样做时,它打印"无法创建文件",这是我使用的代码:

#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();
}
Run Code Online (Sandbox Code Playgroud)

但是当我在同一个程序中输入字符串直接输入QFile变量构造函数时,"File is be Gotated"并且我在桌面上找到它,下面的代码工作正常:

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;
}
Run Code Online (Sandbox Code Playgroud)

我想能够已经有QStrings并附加它们并将它们发送到QFile变量构造函数,有关如何解决我的问题的任何建议吗?谢谢

Nik*_* C. 7

不要硬编码此文件系统位置.相反,在Qt4中你应该使用QDesktopServices:

QString location = 
    QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
Run Code Online (Sandbox Code Playgroud)

在Qt5中,它是QStandardPaths:

QString location = 
    QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
Run Code Online (Sandbox Code Playgroud)

这很重要,因为/ home/username/Desktop不能保证是用户的Desktop文件夹.