How to read user specified file in emscripten assembly?

I am currently working on a C parsing library with support for emscripten compilation. It takes the file path from the user, where he reads the binary file and parses it.

I understand that emscripten does not support direct file downloads, but instead uses a virtual file system. Is there a way to upload the file at the specified path to the virtual file system so that compiled with emscripten C lib can read it? I am looking for solutions for NodeJS and in the browser.

+7
c filesystems emscripten
source share
4 answers

If you want to compile this file directly in the library, you can use the --preload-file or -embed-file option. Like this:

emcc main.cpp -o main.html --preload-file /tmp/ my@ /home/caiiiycuk/test.file 

After that, in C, you can normally open this file:

 fopen("/home/caiiiycuk/test.file", "rb") 

Or you can use emscripten javascript fs-api , for example using ajax:

 $.ajax({ url: "/dataurl", type: 'GET', beforeSend: function (xhr) { xhr.overrideMimeType("text/plain; charset=x-user-defined"); }, success: function( data ) { Module['FS_createDataFile']("/tmp", "test.file", data, true, true); } }); 

After that, you can open this file with C. Also not the best way to transfer data to C-code, you can transfer data directly to memory, read about it .

+5
source share

If you can provide the file by downloading the form from your web page, then when you receive the โ€œdataโ€ file, you can do something like this.

Consult here on how to achieve this.

Sample code for your problem:

 // Assuming data contains the base64 encoded fileData, // you want the file to be present at "." location with name as myFileName Module['FS_createDataFile'](".", myFileName, atob(data), true, true); 

A detailed description of the API used can be found here.

This solution works for browsers where you do not have direct access to the file system.

+3
source share

You can also use the synchronous XHR virtual backup file . Beware that it requires you to execute your code in a web worker. If you want to support multiple files, you can access them using the virtual file system for the archive. The main advantage of this approach is that it will delay the download until the file is read.

+1
source share

Emscripten, today (June 2016), supports a file system called NODEFS , which provides access to the local file system when working on nodejs .

You need to manually mount the NODEFS file system to the root file system. For example:

 EM_ASM( FS.mkdir('/working'); FS.mount(NODEFS, { root: '.' }, '/working'); ); 

Then you can access ./abc from the local file system via the virtual path /working/abc .

+1
source share

All Articles