C++ 在 Qt 中创建/写入新文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4916193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:54:55  来源:igfitidea点击:

Creating/writing into a new file in Qt

c++qt

提问by Tom83B

I am trying to write into a file and if the file doesn't exist create it. I have searched on the internet and nothing worked for me.

我正在尝试写入文件,如果该文件不存在,则创建它。我在互联网上搜索过,但没有任何效果对我有用。

My code looks currently like this:

我的代码目前看起来像这样:

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

If I create a text file called Data in the directory, it remains empty. If I don't create anything it doesn't create the file either. I don't know what to do with this, this isn't the first way in which I tried to create/write into a file and none of the ways worked.

如果我在目录中创建一个名为 Data 的文本文件,它仍然是空的。如果我不创建任何东西,它也不会创建文件。我不知道该怎么办,这不是我尝试创建/写入文件的第一种方法,而且没有一种方法有效。

Thanks for your answers.

感谢您的回答。

采纳答案by shoosh

Are you sure you're in the right directory?
Opening a file without a full path will open it in the current working directory. In most cases this is not what you want. Try changing the first line to

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

QString filename="c:\\Data.txt"or
QString filename="c:/Data.txt"

QString filename="c:\\Data.txt"或者
QString filename="c:/Data.txt"

and see if the file is created in c:\

并查看文件是否在 c:\

回答by Palmik

That is weird, everything looks fine, are you sure it does not work for you? Because this mainsurely works for me, so I would look somewhere else for the source of your problem.

这很奇怪,一切看起来都很好,你确定它不适合你吗?因为这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;
    }
}

The code you provided is also almost the same as the one provided in detailed description of QTextStreamso I am pretty sure, that the problem is elsewhere :)

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

Also note, that the file is not called Databut Data.txtand should be created/located in the directory from which the program was run (not necessarily the one where the executable is located).

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

回答by d.danailov

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

回答by zar

Your code is perfectly fine, you are just not looking at the right location to find your file. Since you haven't provided absolute path, your file will be created relative to the current working folder (more precisely in the current working folder in your case).

您的代码非常好,只是您没有查看正确的位置来找到您的文件。由于您没有提供绝对路径,您的文件将相对于当前工作文件夹(在您的情况下更准确地在当前工作文件夹中)创建。

Your current working folder is set by Qt Creator. Go to Projects >> Your selected build >> Press the 'Run' button (next to 'Build) and you will see what it is on this page which of course you can change as well.

您当前的工作文件夹由 Qt Creator 设置。转到项目>>您选择的构建>>按“运行”按钮(在“构建”旁边),您将在此页面上看到它是什么,当然您也可以更改。

enter image description here

在此处输入图片说明

回答by vsz

It can happen that the cause is not that you don't find the right directory. For example, you can read from the file (even without absolute path) but it seems you cannot write into it.

原因可能不是您没有找到正确的目录。例如,您可以从文件中读取(即使没有绝对路径),但似乎无法写入文件。

In that case, it might be that you program exits before the writing can be finished.

在这种情况下,可能是您的程序在写入完成之前退出。

If your program uses an event loop (like with a GUI application, e.g. QMainWindow) it's not a problem. However, if your program exits immediately after writing to the file, you should flush the text stream, closing the file is not always enough (and it's unnecessary, as it is closed in the destructor).

如果您的程序使用事件循环(如 GUI 应用程序,例如QMainWindow),这不是问题。但是,如果您的程序在写入文件后立即退出,您应该刷新文本流,关闭文件并不总是足够的(而且没有必要,因为它在析构函数中关闭)。

stream << "something" << endl;
stream.flush();

This guarantees that the changes are committed to the file before the program continues from this instruction.

这保证在程序从该指令继续之前将更改提交到文件。

The problem seems to be that the QFile is destructed before the QTextStream. So, even if the stream is flushed in the QTextStream destructor, it's too late, as the file is already closed.

问题似乎是 QFile 在 QTextStream 之前被破坏。因此,即使流在 QTextStream 析构函数中刷新,也为时已晚,因为文件已经关闭。

回答by nilesh suryawanshi

QFile file("test.txt");
/*
 *If file does not exist, it will be created
 */
if (!file.open(QIODevice::ReadOnly | QIODevice::Text | QIODevice::ReadWrite))
{
    qDebug() << "FAILED TO CREATE FILE / FILE DOES NOT EXIST";
}

/*for Reading line by line from text file*/
while (!file.atEnd()) {
    QByteArray line = file.readLine();
    qDebug() << "read output - " << line;
}

/*for writing line by line to text file */
if (file.open(QIODevice::ReadWrite))
{
    QTextStream stream(&file);
    stream << "1_XYZ"<<endl;
    stream << "2_XYZ"<<endl;
}