0

My main.rs:

use std::fs::File;
use std::io::prelude::*;

fn read_file(file_name: &str, file_path: &str) -> Vec<String> {
    let file_open_error = format!("File {} by path {} not found!", file_name, file_path);
    let file_read_error = format!(
        "Can't read the file {}\\{}, the error:{}",
        file_path, file_name
    );

    let mut file = File::open(format!("{}\\{}", file_path, file_name)).expect(&*file_open_error);

    let mut content = String::new();
    file.read_to_string(&mut content).expect(&*file_read_error);

    content
        .split_whitespace()
        .map(|s| s.to_string())
        .collect::<Vec<String>>()
}

fn get_random_value<'a>(vec: &'a Vec<String>) -> &'a String {
    let mut rng = rand::thread_rng();
    rng.choose(&vec).unwrap()
}

fn main() {
    let names_file_name = "names.txt";
    let adjectives_file_name = "adjectives.txt";
    let file_path = "D:\\nameadj";

    let names = read_file(names_file_name, file_path);
    let adjectives = read_file(adjectives_file_name, file_path);

    let name = get_random_value(&names);
    let adjective = get_random_value(&adjectives);
    println!("name={};adjective={}", name, adjective);
}

I've compiled it:

cargo build --release --target wasm32-unknown-emscripten

I've created a simple HTML file where I call the JavaScript file, which I saved here:

target\wasm32-unknown-emscripten\release

When I run it

emrun --browser firefox --port 8080 tryrustwebasm.html

There is an error in the console log of my browser:

thread 'main' panicked at 'File names.txt by path D:\nameadj not found!: Error { repr: Os { code: 2, message: "No such file or directory" } }', /checkout/src/libcore/result.rs:906:4

When I run the program without emrun:

cargo run

the program works fine.

What am I doing wrong? Is this a permissions problem? How do I fix it?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
compasses
  • 99
  • 1
  • 7
  • 4
    Where are you expecting to load this file from? JS code can't load arbitrary files from a user's filesystem, so I wouldn't expect a WASM one to be able to either. – loganfsmyth Jan 15 '18 at 17:41
  • Oh. Here's how. I do not know JS, so it is suddenly for me. Can you tell me what I can do in my case? – compasses Jan 15 '18 at 17:47
  • 1
    I'm not quite confident enough to answer this for the Rust and WASM case, but assuming it is similar to JS, you'll want to take a look at http://kripken.github.io/emscripten-site/docs/porting/emscripten-runtime-environment.html#file-systems The filesystem you're accessing now is likely entirely in-memory, and not the user's actual filesystem. – loganfsmyth Jan 15 '18 at 17:53
  • 3
    Probably a duplicate of [Can I read files from the disk by using Webassembly?](https://stackoverflow.com/q/45535301/155423) – Shepmaster Jan 15 '18 at 18:38

0 Answers0