[![std-badge]][std] [![cat-filesystem-badge]][cat-filesystem]
将一份三行的消息写入文件,然后由BufRead::lines
,返回Lines
迭代器,用来一次读取一行。 File
实现了Read
,也就是提供BufReader
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(())
}