在Qt中创建/写入新文件 [英] Creating/writing into a new file in Qt
问题描述
我正在尝试写入文件,如果文件不存在,请创建它.我在互联网上搜索过,对我没有任何帮助.
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;
}
如果我在目录中创建一个名为Data的文本文件,则该文件为空.如果我不创建任何文件,也不会创建文件.我不知道该怎么办,这不是我尝试创建/写入文件的第一种方法,而且没有一种可行的方法.
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.
感谢您的回答.
推荐答案
您确定自己在正确的目录中吗?
打开没有完整路径的文件将在当前工作目录中将其打开.在大多数情况下,这不是您想要的.尝试将第一行更改为
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"
或 QString filename ="c:/Data.txt"
查看文件是否在 c:\
这篇关于在Qt中创建/写入新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!