在Qt中创建/写入新文件

Tom*_*83B 46 c++ qt

我正在尝试写入文件,如果该文件不存在则创建它.我在互联网上搜索过,没有什么对我有用.

我的代码看起来像这样:

QString filename="Data.txt";
QFile file( filename );
if ( file.open(QIODevice::ReadWrite) )
{
    QTextStream stream( &file );
    stream << "something" << endl;
}
Run Code Online (Sandbox Code Playgroud)

如果我在目录中创建一个名为Data的文本文件,它将保持为空.如果我不创建任何东西,它也不会创建文件.我不知道该怎么做,这不是我尝试创建/写入文件的第一种方式,而且没有一种方法可行.

谢谢你的回答.

Pal*_*mik 25

这很奇怪,一切看起来都很好,你确定它不适合你吗?因为这main肯定对我有用,所以我会在其他地方寻找问题的根源.

#include <QFile>
#include <QTextStream>


int main()
{
    QString filename = "Data.txt";
    QFile file(filename);
    if (file.open(QIODevice::ReadWrite)) {
        QTextStream stream(&file);
        stream << "something" << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

您提供的代码也与QTextStream的详细描述中提供的代码几乎相同,所以我很确定,问题出在其他地方:)

另请注意,文件未被调用,DataData.txt应该在运行程序的目录中创建/定位(不一定是可执行文件所在的目录).


sho*_*osh 23

你确定你在正确的目录中吗?
打开没有完整路径的文件将在当前工作目录中打开它.在大多数情况下,这不是你想要的.尝试将第一行更改为

QString filename="c:\\Data.txt" 要么
QString filename="c:/Data.txt"

并查看文件是否在中创建 c:\

  • 驱动器号不区分大小写 - 但您需要执行"c:\\"或"c:/"以避免\被视为转义 (10认同)
  • @ Tom83B这是预期的行为..exe是创建文本文件的原因,而不是.cpp文件.此外,您应该尝试"C:\ Data.txt",驱动器号可能区分大小写. (3认同)
  • 只是对QT 4.8文档中这个答案的更新:"QFile希望文件分隔符为`/`而不管操作系统.不支持使用其他分隔符(例如'\')." ..所以请确保使用正斜杠`/`作为文件路径.资料来源:http://doc.qt.io/qt-4.8/qfile.html (2认同)

d.d*_*lov 10

#include <QFile>
#include <QCoreApplication>
#include <QTextStream>

int main(int argc, char *argv[])
{
    // Create a new file     
    QFile file("out.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    out << "This file is generated by Qt\n";

    // optional, as QFile destructor will already do it:
    file.close(); 

    //this would normally start the event loop, but is not needed for this
    //minimal example:
    //return app.exec();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 那并没有真正解决OP的问题,您的代码*任何*与他们的代码也没有不同... (3认同)