如何在 Qt 5 中写入和读取 QResource 文件?

2021-12-09 00:00:00 qt5 qt c++ qfile qresource

奇怪,我通过添加现有文件...将所需文件添加到资源中,文件就在那里.我运行 qmake ("Build->Run qmake") 以使文件可用.第一个问题:我无法从输出终端向文件中写入任何内容! 但是当我手动写入文件时,每次运行时输出终端都会显示变化它.第二个问题:它仍然显示 QIODevice::read: device not open !这是我的代码:

#include #include #include #include #include #include void wFile(QString 文件名){QFile nFile(文件名);QTextStream str(&nFile);qDebug() <<"你想在想要的文件中写什么:";str.readLine();if (!nFile.open(QFile::WriteOnly | QFile::Text)){qDebug() <<无法打开文件";返回;}nFile.flush();nFile.close();}无效读取(QString文件名){QFile nFile(文件名);if(!nFile.open(QFile::ReadOnly | QFile::Text)){qDebug() <<无法打开文件进行阅读";返回;}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(n文件名);读取(n文件名);返回 a.exec();}

这是代码的输出终端:

解决方案

保存在

目前,Qt 始终将数据直接存储在可执行文件中,即使在操作系统为资源提供本机支持的 ??Windows、macOS 和 iOS 上也是如此....

It's strange, I add desired file into the resources via Add Existing Files..., the file is there. I run qmake ("Build->Run qmake") to make the file available. The first issue: I can't write anything into the file from output terminal! But when I manually write into the file, the output terminal shows the change every time I run it. Second issue: it still says QIODevice::read: device not open ! Here's my code:

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

And here's output terminal of the code:

解决方案

The files saved in a qresource are read-only since they are part of the executable so you can not write or modify them.

docs:

Currently, Qt always stores the data directly in the executable, even on Windows, macOS, and iOS, where the operating system provides native support for resources. ...

相关文章