Emscripten中的虚拟文件系统

一、加载文件(读数据)

使用fopen,fread等操作。

编译选项中添加:
--preload-file a.data

二、写数据

只有MEMFS文件系统是默认包含的,其他必须使用链接标志使能。

NODEFS:   -lnodefs.js
IDBFS:    -lidbfs.js
WORKERFS: -lworkerfs.js
PROXYFS:  -lproxyfs.js

1、MEMFS

  • 在运行时初始化时,MEMFS是默认挂载在“/”目录下的文件系统。
  • 所有文件都严格存在于内存中,当重新加载页面时,写入它们的任何数据都会丢失。

2、NODEFS

  • NODEFS文件系统只运行在node.js环境中
  • NODEFS允许通过挂载操作,将主机文件系统上的目录映射到Emscripten的虚拟文件系统中的目录。
  • 它使用节点的同步FS API将写入Emscripten文件系统的任何数据写到本地磁盘

代码示例:

/*
 * Copyright 2013 The Emscripten Authors.  All rights reserved.
 * Emscripten is available under two separate licenses, the MIT license and the
 * University of Illinois/NCSA Open Source License.  Both these licenses can be
 * found in the LICENSE file.
 */

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

#ifdef NODERAWFS
#define CWD ""
#else
#define CWD "/working/"
#endif

int main() {
  FILE *file;
  int res;
  char buffer[512];

  // write something locally with node
  EM_ASM(
    var fs = require('fs');
    fs.writeFileSync('foobar.txt', 'yeehaw');
  );
  
#ifndef NODERAWFS
  // mount the current folder as a NODEFS instance
  // inside of emscripten
  EM_ASM(
    FS.mkdir('/working');
    FS.mount(NODEFS, { root: '.' }, '/working');
  );
#endif

  // read and validate the contents of the file
  file = fopen(CWD "foobar.txt", "r");
  assert(file);
  res = fread(buffer, sizeof(char), 6, file);
  assert(res == 6);
  fclose(file);

  assert(!strcmp(buffer, "yeehaw"));

  // write out something new
  file = fopen(CWD "foobar.txt", "w");
  assert(file);
  res = fwrite("cheez nihao webassembly", sizeof(char), 20, file);
  assert(res == 20);
  fclose(file);

  // validate the changes were persisted to the underlying fs
  EM_ASM(
    var fs = require('fs');
    var contents = fs.readFileSync('foobar.txt', { encoding: 'utf8' });
    assert(contents === 'cheez');
  );

  puts("success");

  return 0;
}

编译和运行

编译: emcc test_nodefs_rw.c -o test_nodefs_rw.js -lnodefs.js -s FORCE_FILESYSTEM=1 -s INITIAL_MEMORY=64mb
运行: node test_nodefs_rw.js

3、IDBFS

  • IDBFS文件系统只运行在浏览器中
  • IDBFS文件系统实现了FS.syncfs()接口,当调用该接口时,将把任何操作持久化到IndexedDB实例。
  • 这样做是为了克服浏览器不提供持久存储同步api的限制,因此(默认情况下)所有写操作仅临时存在于内存中。

4、WORKERFS

  • WORKERFS只云习惯在worker线程中
  • 这个文件系统提供了对worker内部的file和Blob对象的只读访问,而不需要将整个数据复制到内存中,并且可以用于巨大的文件。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值