0

I'm currently porting a C project to the web using Emscripten, but the one issue I haven't managed to figure out is why file writing using IDBFS doesn't work. This is the simplest possible C code example of what I'm trying to do currently, but it doesn't work, that is, checking the IndexedDB storage in the Firefox and Chrome web developer tools doesn't show test.txt at all:

#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;
}

I build that example like this:

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

And run it using emrun test.html.

This other example also doesn't work, though I'd prefer to use C functions for opening/writing files:

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

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

That last example requires a change to the build command:

emcc test.c -lidbfs.js -s FORCE_FILESYSTEM=1 --emrun -o test.html
  • Did you use `FS.mount`? https://emscripten.org/docs/api_reference/Filesystem-API.html#id2 – zakki Oct 03 '22 at 11:34

1 Answers1

1

You need to mount a disk to directory before doing any operations on file system.

Something line this

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 ...

There is same thing in emscripten tests.