当我在这里阅读 Rust 教程时(https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html)。我找到了这段代码:
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),
};
}
Run Code Online (Sandbox Code Playgroud)
它总是显示错误:{ code: 2, kind: NotFound, message: "The system cannot find the file specified." }即使我hello.txt在 的根文件夹中创建 a src,它也无法读取它。
在另一个例子中,我cargo run没有成功。程序仍然无法读取hello.txt文件。我知道该示例使用rustc open.rs && ./open. cargo run因为我不明白为什么它突然使用不同的编译方法,它是什么意思......我只是有点跳过它并尝试使用
我需要将文件放在哪里以便cargo run可以读取它?
另外,如果我运行生产代码并需要程序读取外部文件,我需要将其放在哪里?
这是我的文件夹结构。很简单,因为我刚刚开始学习 RUST。先感谢您。
use*_*342 16
名称中不带目录部分的文件需要位于当前工作目录中,即启动可执行文件或cargo run.
如果您从 IDE 启动 Cargo,可能不会立即看出它将使用哪个目录作为当前目录。在这种情况下,您始终可以通过显式打印来找到当前工作目录:
fn main() {
println!("{}", std::env::current_dir().unwrap().display());
}
Run Code Online (Sandbox Code Playgroud)