Search code examples
webassemblyemscriptenwasm-bindgenwasmtime

fopen function is failed to open existing file in read mode (wasm platform)


I have compiled the following code using the emcc compiler

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    if(argc > 2 || argc < 2) {
        printf("\nEnter the name of file \n");
        return 0;
    }
    FILE *file = NULL;
    // Open file in read mode
    printf("file name: %s",argv[1]);
    file = fopen(argv[1], "r");
    if(file != NULL) {
        printf("\nFile is successfully open\n");
    }
    else {
        printf("\nFile is not opening\n");
        return 0;
    }
    fclose(file);
    return 0;
}

i have tried to compile like,

$emcc mycode.c
$node mycode.js input.txt

Output:

file name: input.txt
File is not opening 

there is another way to compile and run like,

$emcc mycode.c --preload-file input.txt -o mycode.html
$node mycode.js input.txt

Output:

file name: input.txt
File is successfully open

but at the time of compilation i have to specify the name of file which is opening in read mode, is there any way to access file from local file system and opening file without giving --preload-file option

thanks in advance

I am expecting to open file using fopen function in read mode from local file system.


Solution

  • Using the native file system is harder and requires more experimental browser features, but can you solve the problem by just passing the directory instead of the file? Then you can at least pick any file in that directory.

    emcc mycode.c --preload-file ./ -o mycode.html
    

    --preload-file also takes directories, despite the name.