本教程通过实例展示了Rust中读取文件的多种方法。
Rust文件读取内容成字符串
Rust提供了一个标准库std ,它提供了一个带有文件读写操作的fs 模块。fs模块中的read_to_string 函数接收文件的路径,并将文件内容转换成一个字符串。如果文件不存在,它会给出一个错误。
下面是一个语法
pub fn read_to_string<P: AsRef<Path>>(path: P) -> Result<String>
它返回String的结果,其中包含一个错误和String。 下面是一个用Rust将文件读成字符串的示例程序。
use std::fs;
fn main() {
let str = fs::read_to_string("test.txt").expect("Error in reading the file");
println!("{}", str);
}
它将字符串显示在控制台中。
如果test.txt文件在当前目录下,上述程序是有效的。
如果没有找到该文件,它会抛出以下错误线程'main'在'无法读取文件'时惊慌失措。Os { code:2, kind:NotFound, message:"系统无法找到指定的文件。"}', test.rs:4:46
Rust文件读取内容到一个矢量
这个例子使用fs 模块中的read 函数将文件内容读到Vec<U8> 。 下面是一个示例程序
use std::fs;
fn main() {
let result = fs::read("test.txt").expect("Error in reading the file");
println!("{}", result.len());
println!("{:?}", result);
}
以上两个对小文件有效,如果你想读取大文件,请使用缓冲区读取。
如何在Rust中使用BufReader逐行读取文件的内容
BufferReader一般都有一个缓冲区,可以有效地读取文件输入和输出操作。
- 创建一个用于存储文件行的mutate字符串
- 创建一个带有路径的文件对象,使用
File::open - 将文件实例传递给
BufReader构造函数 - 用一个保存文件行数据的变量调用BufReader.read_to_string -最后,打印数据
use std::fs::File;
use std::io::{BufReader, Read};
fn main() {
let mut str = String::new();
let file = File::open("test.txt").expect("Error in reading file");
let mut bufferReader = BufReader::new(file);
bufferReader.read_to_string(&mut str).expect("Unable to read line");
println!("{}", str);
}
总结
学习了将文件读成字符串和向量的示例程序,并且在rust中逐行读取内容。