When I was reading through the tutorial for Rust here (https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html). I found this block of code:
use std::fs::File;
fn main() {
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => panic!("Problem opening the file: {:?}", error),
};
}
It always displays an error: { code: 2, kind: NotFound, message: "The system cannot find the file specified." }
even when I make a hello.txt
at the root folder of the src
, it fails to read it.
In another example here, I use cargo run
to no success. The program still fails to read hello.txt
file. I'm aware that the example uses rustc open.rs && ./open
. Since I don't understand why is it suddenly use different compile method and what's it even mean... I just kinda skip it and try to use cargo run
instead
Where do I need to put my file here so cargo run
can read it ?
Also if I run the production code and need the program to read an external file, where do I need to put it ?
Here's my folder structure. Pretty simple since I just start to learn RUST. Thank you in advance.
Closing the file is done by dropping the std::fs::File , which you probably do not want or can do in the data structure you have. To avoid conflicts as you describe, you could wrap the File in a std::cell::RefCell and use try_borrow_mut() whenever you want to write to File , and try_borrow() whenever reading from it.
A file without a directory component in the name needs to be in the current working directory, i.e. the directory from which you start your executable or cargo run
.
If you start cargo from an IDE, it might not be immediately apparent what directory it will use as the current directory. In that case, you can always find the current working directory by printing it explicitly:
fn main() {
println!("{}", std::env::current_dir().unwrap().display())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With