Writting in text file error, QT

前端 未结 1 488
盖世英雄少女心
盖世英雄少女心 2020-12-12 06:40

I have this code in QT c++

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


        
相关标签:
1条回答
  • 2020-12-12 07:20

    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"));
    
    0 讨论(0)
提交回复
热议问题