简体   繁体   English

Rust 需要读取的文件在哪里?

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

When I was reading through the tutorial for Rust here ( https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html ).当我在这里阅读 Rust 的教程时( https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.ZFC35FDC70D5FC69D2698Z83A822 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." }它总是显示错误: { code: 2, kind: NotFound, message: "The system cannot find the file specified." } { 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.即使我在src的根文件夹中hello.txt { code: 2, kind: NotFound, message: "The system cannot find the file specified." }它也无法读取它。

In another example here , I use cargo run to no success.这里的另一个例子中,我使用cargo run没有成功。 The program still fails to read hello.txt file.程序仍然无法读取hello.txt文件。 I'm aware that the example uses rustc open.rs &&./open .我知道该示例使用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因为我不明白为什么它突然使用不同的编译方法,甚至是什么意思......我只是有点跳过它并尝试使用cargo run代替

Where do I need to put my file here so cargo run can read it?我需要把我的文件放在哪里,以便cargo run可以读取它?

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.很简单,因为我刚开始学习 RUST。 Thank you in advance.先感谢您。

文件夹结构

A file without a directory component in the name needs to be in the current working directory , ie the directory from which you start your executable or cargo run .名称中没有目录组件的文件需要位于当前工作目录中,即您启动可执行文件或cargo run的目录。

If you start cargo from an IDE, it might not be immediately apparent what directory it will use as the current directory.如果您从 IDE 启动 cargo,可能不会立即看出它将使用哪个目录作为当前目录。 In that case, you can always find the current working directory by printing it explicitly:在这种情况下,您始终可以通过显式打印找到当前工作目录:

fn main() {
    println!("{}", std::env::current_dir().unwrap().display())
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM