Use Emscripten and WebAssembly to Do File I/O in the Browser

In this Shortcut, we are going to do something you probably thought was not possible. We are going to use the Emscripten toolchain to read and write files with C++ while running in the browser. If you are skeptical, you should be. After all, we cannot change the laws of physics, Captain. Browsers do not actually let us interact with the filesystem. But if we keep that a secret, the C++ code will never know. It will happily execute in the browser.

Before we get started, I need to warn you up front: I am not going to show you entirely how this works here, but in upcoming Shortcuts I will. For now, let’s see how Emscripten generates some scaffolding code to let it happen.

In the GitHub repository for this Shortcut, you should enter the directory 16-Files_CPP. Here, you will see a fairly conventional C++ file called copy.cpp. This is just a simple file that we will look at how to build by hand:

#include <fstream> 
#include <iostream> 
using namespace std; 
  
int main() 
{ 
    string line; 
    ifstream infile("copy.cpp");
    ofstream outfile("copy.txt"); 
 
    if( infile && outfile ) { 
        while (getline(infile, line)) { 
            outfile << line << "\n"; 
        } 
        cout << "Done\n"; 
    } 
    else { 
        printf("File is not readable"); 
    } 
    infile.close(); 
    outfile.close(); 
    return 0; 
}

I obviously cannot teach you C++ or explain its standard stream handling here, but the short version of what is going on is that we ...

Get Use Emscripten and WebAssembly to Do File I/O in the Browser now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.