如何在 Qt 5 中写入和读取 to/from QResource 文件?
How to write and read to/from a QResource file in Qt 5?
很奇怪,我通过添加现有文件...将所需文件添加到资源中,文件就在那里。我 运行 qmake ("Build->Run qmake") 使文件可用。
第一个问题:我无法从输出终端向文件写入任何内容!但是当我手动写入文件时,输出终端显示我每次改运行吧。第二个问题:它仍然说 QIODevice::read: device not open !
这是我的代码:
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <iostream>
void wFile(QString Filename)
{
QFile nFile(Filename);
QTextStream str(&nFile);
qDebug() << "what do you want to write in the desired file: ";
str.readLine();
if (!nFile.open(QFile::WriteOnly | QFile::Text))
{
qDebug() << "could not open the file";
return;
}
nFile.flush();
nFile.close();
}
void read (QString Filename){
QFile nFile(Filename);
if(!nFile.open(QFile::ReadOnly | QFile::Text))
{
qDebug() << "could not open file for reading";
return;
}
QTextStream in(&nFile);
QString nText = in.readAll();
qDebug() << nText;
nFile.close();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString nFilename =":/MyFiles/DocumentArminV.txt";
wFile(nFilename);
read(nFilename);
return a.exec();
}
这里是代码的输出终端:
很奇怪,我通过添加现有文件...将所需文件添加到资源中,文件就在那里。我 运行 qmake ("Build->Run qmake") 使文件可用。 第一个问题:我无法从输出终端向文件写入任何内容!但是当我手动写入文件时,输出终端显示我每次改运行吧。第二个问题:它仍然说 QIODevice::read: device not open ! 这是我的代码:
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <iostream>
void wFile(QString Filename)
{
QFile nFile(Filename);
QTextStream str(&nFile);
qDebug() << "what do you want to write in the desired file: ";
str.readLine();
if (!nFile.open(QFile::WriteOnly | QFile::Text))
{
qDebug() << "could not open the file";
return;
}
nFile.flush();
nFile.close();
}
void read (QString Filename){
QFile nFile(Filename);
if(!nFile.open(QFile::ReadOnly | QFile::Text))
{
qDebug() << "could not open file for reading";
return;
}
QTextStream in(&nFile);
QString nText = in.readAll();
qDebug() << nText;
nFile.close();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString nFilename =":/MyFiles/DocumentArminV.txt";
wFile(nFilename);
read(nFilename);
return a.exec();
}
这里是代码的输出终端: