Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

c++ - Writting in text file error, QT

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...