文件读写
读取文件的字符串行
我们向文件写入三行信息,然后使用 BufRead::lines
创建的迭代器 Lines
读取文件,一次读回一行。File
模块实现了提供 BufReader
结构体的 Read
trait。File::create
打开文件 File
进行写入,File::open
则进行读取。
use std::fs::File;
use std::io::{Write, BufReader, BufRead, Error};
fn main() -> Result<(), Error> {
let path = "lines.txt";
let mut output = File::create(path)?;
write!(output, "Rust\n💖\nFun")?;
let input = File::open(path)?;
let buffered = BufReader::new(input);
for line in buffered.lines() {
println!("{}", line?);
}
Ok(())
}
避免读取写入同一文件
对文件使用 same_file::Handle
结构体,可以测试文件句柄是否等同。在本实例中,将对要读取和写入的文件句柄进行相等性测试。
use same_file::Handle;
use std::fs::File;
use std::io::{BufRead, BufReader, Error, ErrorKind};
use std::path::Path;
fn main() -> Result<(), Error> {
let path_to_read = Path::new("new.txt");
let stdout_handle = Handle::stdout()?;
let handle = Handle::from_path(path_to_read)?;
if stdout_handle == handle {
return Err(Error::new(
ErrorKind::Other,
"You are reading and writing to the same file",
));
} else {
let file = File::open(&path_to_read)?;
let file = BufReader::new(file);
for (num, line) in file.lines().enumerate() {
println!("{} : {}", num, line?.to_uppercase());
}
}
Ok(())
}
cargo run
显示文件 new.txt 的内容。
cargo run >> ./new.txt
报错,因为是同一文件。
使用内存映射随机访问文件
使用 memmap 创建文件的内存映射,并模拟文件的一些非序列读取。使用内存映射意味着您仅需索引一个切片,而不是使用 seek
方法来导航整个文件。
Mmap::map
函数假定内存映射后的文件没有被另一个进程同时更改,否则会出现竞态条件。