使用Emscripten IDBFS/IndexedDB写入文件

kd3sttzy  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(1)|浏览(167)

我目前正在使用Emscripten将一个C项目移植到web上,但我还没有弄清楚的一个问题是为什么使用IDBFS写文件不起作用。这是我目前尝试做的最简单的C代码示例,但它不起作用,也就是说,在Firefox和Chrome web开发工具中检查IndexedDB存储根本不显示test.txt

#include <emscripten.h>
#include <stdio.h>

int main() {
    FILE* fp = fopen("/test.txt", "w");
    if (fp) {
        fprintf(fp, "test\n");
        fclose(fp);

        EM_ASM(
            FS.syncfs(function (err) {
                assert(!err);
            });
        );
    }
    else {
        printf("fopen failed.\n");
    }
    return 0;
}

我构建示例如下:

emcc test.c -lidbfs.js --emrun -o test.html

并使用emrun test.html运行它。
另一个例子也不起作用,尽管我更喜欢使用C函数来打开/写入文件:

#include <emscripten.h>
#include <stdio.h>

int main() {
    EM_ASM(
        FS.writeFile('test.txt', 'test\n');
        FS.syncfs(function (err) {
            assert(!err);
        });
    );
    return 0;
}

最后一个示例需要对build命令进行更改:

emcc test.c -lidbfs.js -s FORCE_FILESYSTEM=1 --emrun -o test.html
sg3maiej

sg3maiej1#

在文件系统上执行任何操作之前,您需要将磁盘装载到目录。
这条线上有东西

int main() {
EM_ASM(
        // Make a directory other than '/'
        FS.mkdir('/disk');
        // Then mount with IDBFS type
        FS.mount(IDBFS, {}, '/disk');
           
        // Then sync
        FS.syncfs(true, function (err) {
            // Error
        });
    );
    FILE* fp = fopen("/disk/test.txt", "w");
    if (fp) {
        fprintf(fp, "test\n");
        fclose(fp);

// your code continue here ...

在emscripten测试中也有同样的事情。

相关问题