Reputation: 727
Rust newbie here. I am trying to open a file with:
let file = File::open("file.txt").unwrap();
Due to my build setup it looks like my binary and txt are not where I expect it to be or I am doing something wrong so I am getting a:
thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: Error { repr: Os { code: 2, message: "No such file or directory" } }', ../src/libcore/result.rs:736
The error message does not say anything about what the expected path where the txt has to live should be so that my program and tests see it. How can I print this expected path? I would like to print a message like:
The file "/expected/folder/file.txt" does not exist
Upvotes: 2
Views: 576
Reputation: 2701
Just match returned Result
explicitly against required error like this:
use std::fs::File;
use std::io::ErrorKind;
fn main() {
match File::open("file.txt") {
Ok(file) =>
println!("The file is of {} bytes", file.metadata().unwrap().len()),
Err(ref e) if e.kind() == ErrorKind::NotFound =>
println!("The file {}/file.txt does not exist", std::env::current_dir().unwrap().display()),
Err(e) =>
panic!("unexpected error: {:?}", e),
}
}
Upvotes: 7