写文本文件错误,QT [英] Writting in text file error, QT

查看:42
本文介绍了写文本文件错误,QT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在QT c ++中有此代码

I have this code in QT c++

void writeInFile()
{
    QFile file(":/texts/test.txt");
    if(file.open(QIODevice::ReadWrite))
    {
        QTextStream in(&file);
        in<<"test";
    }
    file.close();
}

我想在带有前缀"texts"的资源中的文本文件中添加"test",但是此功能不起作用,当我在文件中添加"QIODevice :: ReadWrite"时,我无法从文件中读取或读取文件或"QFile :: ReadWrite",我只能在只读模式下从中读取.欢迎任何帮助或建议.

I want to add "test" to my text file which is in resources with prefix "texts", but this function does nothing, I can't write or read from file when I am oppening it with "QIODevice::ReadWrite" or "QFile::ReadWrite", I can only read from it on readonly mode. Any help or advice welcome.

推荐答案

Qt资源文件是只读的,因为它们作为代码"放入二进制文件中-应用程序无法自行修改.

Qt resource files are read-only, as they are put into the binary as "code" - and the application cannot modify itself.

由于根本不可能编辑资源,因此您应该遵循缓存这些文件的标准方法.这意味着您将资源复制到本地计算机并对其进行编辑.

Since editing resources is simply impossible, you should follow the standard approach of caching those files. This means you copy the resource to the local computer and edit that one.

这是一个基本功能,完全可以做到:

Here is a basic function that does exactly that:

QString cachedResource(const QString &resPath) {
    // not a ressource -> done
    if(!resPath.startsWith(":"))
        return resPath;
    // the cache directory of your app
    auto resDir = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
    auto subPath = resDir + "/resources" + resPath.mid(1); // cache folder plus resource without the leading :
    if(QFile::exists(subPath)) // file exists -> done
        return subPath;
    if(!QFileInfo(subPath).dir().mkpath("."))
        return {}; //failed to create dir
    if(!QFile::copy(resPath, subPath))
        return {}; //failed to copy file
    // make the copied file writable
    QFile::setPermissions(subPath, QFileDevice::ReadUser | QFileDevice::WriteUser);
    return subPath;
}

简而言之,如果资源不存在,则将其复制到缓存位置,然后将路径返回到该缓存的资源.要注意的一件事是,复制操作会保留只读"权限,这意味着我们必须手动设置权限.如果您需要其他权限(例如,执行或访问组/全部),则可以调整该行.

In short, it copies the resource to a cache location if it does not already exist there and returns the path to that cached resource. One thing to be aware of is that the copy operation presevers the "read-only" permission, which means we have to set permissions manually. If you need different permissions (i.e. execute, or access for the group/all) you can adjust that line.

在您的代码中,您将更改以下行:

In your code, you would change the line:

QFile file(cachedResource(":/texts/test.txt"));

这篇关于写文本文件错误,QT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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