file - Rust 读取文件

标签 file io compiler-errors rust

<分区>

我正在尝试读取一个名为 enable.txt 的文件,该文件与我的 main.rs 位于同一目录中,我的代码如下所示:

use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::error::Error;
fn main() {
    let path = Path::new("enable.txt");
    let display = path.display();
    let mut file = File::open(&path);
    let mut contents = String::new();
    file.read_to_string(&mut contents);
    println!("{}", contents);
}

当我使用 cargo runrustc src/main.rs 编译它时,我收到此错误消息:

error: no method named `read_to_string` found for type `std::result::Result<std::fs::File, std::io::Error>` in the current scope
  --> src/main.rs:10:10
   |
10 |     file.read_to_string(&mut contents);
   |          ^^^^^^^^^^^^^^

最佳答案

问题是 File::open()返回 std::result::Result<std::fs::File, std::io::Error>需要以某种方式解包才能访问文件。我更喜欢这样做的方式是使用 expect()像这样:

...
fn main() {
    ...
    let mut file = File::open(&path).expect("Error opening File");
    ...
    file.read_to_string(&mut contents).expect("Unable to read to string");
    ...
}

这将返回预期值或 panic根据操作是否成功提供错误消息。

关于file - Rust 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44340721/

相关文章:

c++ - 从文件中读取和写入 int 对

c - O_DIRECT 标志不起作用

java - 打开包含文件的文件夹并突出显示它

java - 选择非阻塞 FileDescriptors

arrays - 调用 sub 后 Excel 工作簿编译错误

oracle - 如何清除SQLPlus中的错误消息缓冲区?

file - 使用 Google Translate API 翻译 PDF 文件

c - 如何在C中读取数字到字符串直到行尾

c - 扫描名称和奇怪的字符串: Files

c - (.text+0x20) : undefined reference to `main' and undefined reference to function