繁体   English   中英

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

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

当我在这里阅读 Rust 的教程时( https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.ZFC35FDC70D5FC69D2698Z83A822 我找到了这段代码:

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),
   };
}

它总是显示错误: { code: 2, kind: NotFound, message: "The system cannot find the file specified." } 即使我在src的根文件夹中hello.txt { code: 2, kind: NotFound, message: "The system cannot find the file specified." }它也无法读取它。

这里的另一个例子中,我使用cargo run没有成功。 程序仍然无法读取hello.txt文件。 我知道该示例使用rustc open.rs &&./open 因为我不明白为什么它突然使用不同的编译方法,甚至是什么意思......我只是有点跳过它并尝试使用cargo run代替

我需要把我的文件放在哪里,以便cargo run可以读取它?

另外,如果我运行生产代码并需要程序读取外部文件,我需要把它放在哪里?

这是我的文件夹结构。 很简单,因为我刚开始学习 RUST。 先感谢您。

文件夹结构

名称中没有目录组件的文件需要位于当前工作目录中,即您启动可执行文件或cargo run的目录。

如果您从 IDE 启动 cargo,可能不会立即看出它将使用哪个目录作为当前目录。 在这种情况下,您始终可以通过显式打印找到当前工作目录:

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

暂无
暂无

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

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