Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save usagi/4319834ef30abef49c64 to your computer and use it in GitHub Desktop.
Save usagi/4319834ef30abef49c64 to your computer and use it in GitHub Desktop.
Hello, Filesystem or Web Local Storage! with emscripten_run_script_string version.
#include <iostream>
#include <fstream>
#include <string>
#ifdef EMSCRIPTEN
#include <emscripten/emscripten.h>
#endif
namespace
{
auto save( const std::string& path, const std::string& data )
-> void
{
#ifndef EMSCRIPTEN
std::ofstream f;
f.exceptions( std::ofstream::failbit | std::ofstream::badbit );
f.open( path, std::ofstream::binary );
f.write( data.data(), data.size() );
#else
//EM_ASM_ARGS
//( { localStorage.setItem( Pointer_stringify( $0 ), Pointer_stringify( $1 ) ); }
//, path.data()
//, data.data()
//);
std::string asm_code;
asm_code += "localStorage.setItem( '";
asm_code += path;
asm_code += "', '";
asm_code += data;
asm_code += "' );";
emscripten_run_script( asm_code.data() );
#endif
}
auto load( const std::string& path )
-> std::string
{
#ifndef EMSCRIPTEN
std::ifstream f;
f.exceptions( std::ifstream::failbit | std::ifstream::badbit );
f.open( path, std::ifstream::binary );
f.seekg( 0, std::ifstream::end );
const auto size = f.tellg();
f.seekg( 0, std::ifstream::beg );
std::string buffer;
buffer.resize( size );
f.read( const_cast< char* >( buffer.data() ), size );
#else
std::string asm_code;
asm_code += "localStorage.getItem( '";
asm_code += path;
asm_code += "' );";
std::string buffer = emscripten_run_script_string( asm_code.data() );
#endif
return buffer;
}
}
auto main()
-> int
{
const auto path = "example.data";
const auto data = "Hello, Filesystem or Web Local Storage!";
save( path, data );
std::cout << load( path );
}
Hello, Filesystem or Web Local Storage!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment