简介
在本实验中,将介绍 open 函数,它通过提供所需文件的路径以只读模式打开文件。该函数返回一个拥有文件描述符的 File 对象,并在不再需要时负责关闭文件。
要使用 open 函数,需要导入必要的模块,如 std::fs::File、std::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进行编译和运行。
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 中练习更多实验以提升你的技能。