How to write and read to/from a QResource file in Qt 5?

孤者浪人 提交于 2019-12-04 05:17:25

问题


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:


回答1:


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. ...



来源:https://stackoverflow.com/questions/52148390/how-to-write-and-read-to-from-a-qresource-file-in-qt-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!