Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I need to put file to be read by Rust?

Tags:

rust

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.

folder structure

like image 857
DennyHiu Avatar asked Mar 21 '21 04:03

DennyHiu


People also ask

How do you close a file in Rust?

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.


Video Answer


1 Answers

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())
}
like image 167
user4815162342 Avatar answered Oct 01 '22 05:10

user4815162342