File IO in Emscripten Applications

Emscripten is an amazing tool for compiling C/C++ code to Javascript. File IO is a little tricky, firstly for C++ there isn't any support for C++ iostreams. The next problem is the file can't be ready when running the Javascript in node.

Emscripten has a very nice mechanism for adding files to code compiled to .html , simply create a directory and specify tell the compiler using the --preload-file option.

emcc -o test.html test.cc --preload-file assets
#include<iostream>
#include<cstdio>
#include<vector>

using namespace std;

int main(int argc, char** argv) {
  const char* fname = "assets/text.txt";
  FILE* fp = fopen(fname, "r");
  if (!fp) {
    cerr << "Failed to open file " << fname;
    return 1;
  }
  vector<char> buffer;
  buffer.resize(4096);
  while (fgets(&buffer[0], 4906, fp)) {
    printf("%s", &buffer[0]);
  }
  return 0;
}
There are few issues I'm not sure about still:
  • What are the file size imitations when embedding into HTML?
  • How to access files using a command line interpretor such as node or V8?