【问题标题】:QFile doesn’t create the fileQFile 不创建文件
【发布时间】:2013-06-09 18:16:40
【问题描述】:

我正在编写一个简单的程序。该程序有 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();
}

但是当我在它打印的同一个程序中将字符串直接键入 QFile 变量构造函数时,“文件已创建”并且我在桌面上找到它时,下面的代码可以正常工作:

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;
}

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

【问题讨论】:

  • 我认为你的第一个代码 sn-p 有错误:"/home/mahmoud/Destkop" 应该是"/home/mahmoud/Desktop"

标签: qt


【解决方案1】:

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

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

在 Qt5 中,它是 QStandardPaths:

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

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

【讨论】:

    【解决方案2】:

    您的代码中有输入错误:Destkop 应该是 Desktop。 Qt 无法在不存在的目录中创建文件。

    【讨论】:

    • 感谢您看到输入错误。在发布其他任何内容之前,我会确保查找错误。再次感谢您。
    猜你喜欢
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2011-04-08
    相关资源
    最近更新 更多