我在这里展示的函数没有一个是独立的,但我使用expect
,因为我不知道哪种错误处理方式最适合您的应用程序.阅读The Rust Programming Language's chapter on error handling,了解如何正确处理自己程序中的故障.
Rust 1.26 and onwards
如果你不想关心潜在的细节,有一行函数用于阅读和写作.
Read a file to a String
use std::fs;
fn main() {
let data = fs::read_to_string("/etc/hosts").expect("Unable to read file");
println!("{}", data);
}
Read a file as a Vec<u8>
use std::fs;
fn main() {
let data = fs::read("/etc/hosts").expect("Unable to read file");
println!("{}", data.len());
}
写一个文件
use std::fs;
fn main() {
let data = "Some data!";
fs::write("/tmp/foo", data).expect("Unable to write file");
}
Rust 1.0 and onwards
这些表单比为您分配String
或Vec
的单行函数稍微详细一些,但更强大的是,您可以重用分配的数据或附加到现有对象.
读取数据
读取文件需要两个核心部分:File
和Read
.
Read a file to a String
use std::fs::File;
use std::io::Read;
fn main() {
let mut data = String::new();
let mut f = File::open("/etc/hosts").expect("Unable to open file");
f.read_to_string(&mut data).expect("Unable to read string");
println!("{}", data);
}
Read a file as a Vec<u8>
use std::fs::File;
use std::io::Read;
fn main() {
let mut data = Vec::new();
let mut f = File::open("/etc/hosts").expect("Unable to open file");
f.read_to_end(&mut data).expect("Unable to read data");
println!("{}", data.len());
}
写一个文件
写一个文件是类似的,除了我们使用Write
字符,我们总是写字节.您可以使用as_bytes
将String
/&str
转换为字节:
use std::fs::File;
use std::io::Write;
fn main() {
let data = "Some data!";
let mut f = File::create("/tmp/foo").expect("Unable to create file");
f.write_all(data.as_bytes()).expect("Unable to write data");
}
缓冲I/O
我觉得社区有点推动我使用BufReader
和BufWriter
,而不是直接从文件中阅读
缓冲读取器(或写入器)使用缓冲区来减少I/O请求的数量.例如,一次访问磁盘读取256字节要比访问磁盘256次有效得多.
话虽如此,我不相信缓冲读写器在读取整个文件时会有用.read_to_end
似乎以较大的块复制数据,因此传输可能已经自然地合并为更少的I/O请求.
下面是一个使用它阅读的例子:
use std::fs::File;
use std::io::{BufReader, Read};
fn main() {
let mut data = String::new();
let f = File::open("/etc/hosts").expect("Unable to open file");
let mut br = BufReader::new(f);
br.read_to_string(&mut data).expect("Unable to read string");
println!("{}", data);
}
至于写作:
use std::fs::File;
use std::io::{BufWriter, Write};
fn main() {
let data = "Some data!";
let f = File::create("/tmp/foo").expect("Unable to create file");
let mut f = BufWriter::new(f);
f.write_all(data.as_bytes()).expect("Unable to write data");
}
当你想逐行阅读时,BufReader
更有用:
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let f = File::open("/etc/hosts").expect("Unable to open file");
let f = BufReader::new(f);
for line in f.lines() {
let line = line.expect("Unable to read line");
println!("Line: {}", line);
}
}