Qt Android 无法加载 assets 目录下 lua 校准脚本

发布于:2024-04-26 ⋅ 阅读:(26) ⋅ 点赞:(0)

问题描述

C 语言使用 fopen 无法打开 assets 目录下的文件。

项目的校准脚本在打包的时候都放在 assets 资源目录下,但是 assets 是压缩包,Android 下虚拟目录,所以 Qt 可以加载 assets 目录下文件,但是 C 语言的 fropen 函数却无法打开。

解决方案

为此只能将所有的脚本文件移动到内部存储器中保存,然后从内存存储器中加载校准脚本可以使用。

为了实现这个目的,需要修改原有的逻辑,程序在运行时将判断该存储器中是否存在校准脚本,如果不存在则从 assets 资源目录下复制过来。

  1. 复制目录函数。
#ifdef __ANDROID__
//(源文件目录路劲,目的文件目录,文件存在是否覆盖)
bool copyDirectory(const QString& srcPath, const QString& dstPath, bool coverFileIfExist = true)
{
    QDir srcDir(srcPath);
    QDir dstDir(dstPath);
    qInfo() << srcPath << dstPath;
    if (!dstDir.exists()) { //目的文件目录不存在则创建文件目录
        if (!dstDir.mkdir(dstDir.absolutePath())) {
            qInfo() << "create " << dstDir << " failed";
            return false;
        }
    }
    QFileInfoList fileInfoList = srcDir.entryInfoList();
    foreach(QFileInfo fileInfo, fileInfoList) {
        if (fileInfo.fileName() == "." || fileInfo.fileName() == "..")
            continue;

        if (fileInfo.isDir()) {    // 当为目录时,递归的进行copy
            if (!copyDirectory(fileInfo.filePath(), dstDir.filePath(fileInfo.fileName()), coverFileIfExist))
                return false;
        }
        else {            //当允许覆盖操作时,将旧文件进行删除操作
            if (coverFileIfExist && dstDir.exists(fileInfo.fileName())) {
                dstDir.remove(fileInfo.fileName());
            }
            /// 进行文件copy
            qInfo() << "copy " << fileInfo.filePath() << " to " << dstDir.filePath(fileInfo.fileName());
            if (!QFile::copy(fileInfo.filePath(), dstDir.filePath(fileInfo.fileName()))) {
                qInfo() << "copy failed." << fileInfo.fileName() << dstDir.filePath(fileInfo.fileName()) << fileInfo.filePath();
                return false;
            }
        }
    }
    return true;
}
#endif

  1. main 函数中复制校准脚本,只判断其中一个脚本。
int main(int argc, char *argv[])
{
#ifdef __ANDROID__
    // 如果校准脚本不存在,复制校准脚本
    QString scriptPath = "/storage/emulated/0/UPCNC3/script";
    if(!QFile::exists(scriptPath + "/Calculate.lua"))
        copyDirectory("assets:/script/", scriptPath);
#endif
    //...
}

  1. 设置校准时从 /storage/emulated/0/UPCNC3/script 目录下加载脚本脚本。
#ifdef __ANDROID__
        obj["rootdir"] = "/storage/emulated/0/UPCNC3";
#else
        obj["rootdir"] = m_sDir;
#endif