如何在 Qt 5 中写入和读取 QResource 文件? [英] How to write and read to/from a QResource file in Qt 5?

查看:81
本文介绍了如何在 Qt 5 中写入和读取 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. ...

这篇关于如何在 Qt 5 中写入和读取 QResource 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆