在 Rust 中读取文件

RustRustBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,将介绍 open 函数,它通过提供所需文件的路径以只读模式打开文件。该函数返回一个拥有文件描述符的 File 对象,并在不再需要时负责关闭文件。

要使用 open 函数,需要导入必要的模块,如 std::fs::Filestd::io::prelude::*std::path::Path。然后使用路径作为参数调用 File::open 方法。如果文件成功打开,该函数将返回一个 Result<File, io::Error> 对象,否则,它将因错误消息而恐慌。

文件打开后,可以使用 read_to_string 方法读取其内容。此方法将文件内容读入字符串并返回一个 Result<usize, io::Error>。如果读取操作成功,字符串将包含文件内容。否则,它将因错误消息而恐慌。

在提供的示例中,读取了 hello.txt 文件的内容并打印到控制台。使用 drop 特性确保当 file 对象超出作用域时关闭文件。

注意:如果实验未指定文件名,你可以使用任何你想要的文件名。例如,你可以使用 main.rs,使用 rustc main.rs &&./main 进行编译和运行。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/DataStructuresandEnumsGroup(["Data Structures and Enums"]) rust(("Rust")) -.-> rust/BasicConceptsGroup(["Basic Concepts"]) rust(("Rust")) -.-> rust/DataTypesGroup(["Data Types"]) rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust(("Rust")) -.-> rust/MemorySafetyandManagementGroup(["Memory Safety and Management"]) rust(("Rust")) -.-> rust/ErrorHandlingandDebuggingGroup(["Error Handling and Debugging"]) rust(("Rust")) -.-> rust/AdvancedTopicsGroup(["Advanced Topics"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("Variable Declarations") rust/BasicConceptsGroup -.-> rust/mutable_variables("Mutable Variables") rust/DataTypesGroup -.-> rust/string_type("String Type") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("Lifetime Specifiers") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("Method Syntax") rust/ErrorHandlingandDebuggingGroup -.-> rust/panic_usage("panic! Usage") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("Traits for Operator Overloading") subgraph Lab Skills rust/variable_declarations -.-> lab-99270{{"在 Rust 中读取文件"}} rust/mutable_variables -.-> lab-99270{{"在 Rust 中读取文件"}} rust/string_type -.-> lab-99270{{"在 Rust 中读取文件"}} rust/function_syntax -.-> lab-99270{{"在 Rust 中读取文件"}} rust/expressions_statements -.-> lab-99270{{"在 Rust 中读取文件"}} rust/lifetime_specifiers -.-> lab-99270{{"在 Rust 中读取文件"}} rust/method_syntax -.-> lab-99270{{"在 Rust 中读取文件"}} rust/panic_usage -.-> lab-99270{{"在 Rust 中读取文件"}} rust/operator_overloading -.-> lab-99270{{"在 Rust 中读取文件"}} end

open 函数

open 函数可用于以只读模式打开文件。

一个 File 对象拥有一个资源,即文件描述符,并在其被 drop 时负责关闭文件。

use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

fn main() {
    // 创建指向所需文件的路径
    let path = Path::new("hello.txt");
    let display = path.display();

    // 以只读模式打开路径,返回 `io::Result<File>`
    let mut file = match File::open(&path) {
        Err(why) => panic!("无法打开 {}: {}", display, why),
        Ok(file) => file,
    };

    // 将文件内容读入字符串,返回 `io::Result<usize>`
    let mut s = String::new();
    match file.read_to_string(&mut s) {
        Err(why) => panic!("无法读取 {}: {}", display, why),
        Ok(_) => print!("{} 包含:\n{}", display, s),
    }

    // `file` 超出作用域,"hello.txt" 文件被关闭
}

以下是预期的成功输出:

$ echo "Hello World!" > hello.txt
$ rustc open.rs && ./open
hello.txt 包含:
Hello World!

(鼓励你在不同的失败条件下测试前面的示例:hello.txt 不存在,或 hello.txt 不可读等。)

总结

恭喜你!你已完成“打开文件(Open)”实验。你可以在 LabEx 中练习更多实验以提升你的技能。