本文简要介绍rust语言中 Struct std::io::LineWriter
的用法。
用法
pub struct LineWriter<W: Write> { /* fields omitted */ }
包装写入器并将输出缓冲到它,每当检测到换行符(0x0a
,'\n'
)时刷新。
BufWriter
结构包装了一个 writer 并缓冲其输出。但它仅在超出范围或内部缓冲区已满时才进行批量写入。有时,您更愿意在完成后写入每一行,而不是一次写入整个缓冲区。输入 LineWriter
。它正是这样做的。
与 BufWriter
一样,当 LineWriter
超出范围或其内部缓冲区已满时,也会刷新 LineWriter
的缓冲区。
如果删除 LineWriter
时缓冲区中仍有部分行,它将刷新这些内容。
例子
我们可以使用LineWriter
一次写入一行,显著减少实际写入文件的次数。
use std::fs::{self, File};
use std::io::prelude::*;
use std::io::LineWriter;
fn main() -> std::io::Result<()> {
let road_not_taken = b"I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I -
I took the one less traveled by,
And that has made all the difference.";
let file = File::create("poem.txt")?;
let mut file = LineWriter::new(file);
file.write_all(b"I shall be telling this with a sigh")?;
// No bytes are written until a newline is encountered (or
// the internal buffer is filled).
assert_eq!(fs::read_to_string("poem.txt")?, "");
file.write_all(b"\n")?;
assert_eq!(
fs::read_to_string("poem.txt")?,
"I shall be telling this with a sigh\n",
);
// Write the rest of the poem.
file.write_all(b"Somewhere ages and ages hence:
Two roads diverged in a wood, and I -
I took the one less traveled by,
And that has made all the difference.")?;
// The last line of the poem doesn't end in a newline, so
// we have to flush or drop the `LineWriter` to finish
// writing.
file.flush()?;
// Confirm the whole poem was written.
assert_eq!(fs::read("poem.txt")?, &road_not_taken[..]);
Ok(())
}
相关用法
- Rust LineWriter.new用法及代码示例
- Rust LineWriter.with_capacity用法及代码示例
- Rust LineWriter.get_mut用法及代码示例
- Rust LineWriter.get_ref用法及代码示例
- Rust LineWriter.into_inner用法及代码示例
- Rust LinkedList.push_front用法及代码示例
- Rust LinkedList.remove用法及代码示例
- Rust LinkedList.front用法及代码示例
- Rust LinkedList.is_empty用法及代码示例
- Rust LinkedList.back_mut用法及代码示例
- Rust LinkedList.pop_front用法及代码示例
- Rust LinkedList.new用法及代码示例
- Rust LinkedList.clear用法及代码示例
- Rust LinkedList.iter_mut用法及代码示例
- Rust LinkedList.drain_filter用法及代码示例
- Rust LinkedList.back用法及代码示例
- Rust LinkedList.front_mut用法及代码示例
- Rust LinkedList.iter用法及代码示例
- Rust LinkedList.split_off用法及代码示例
- Rust LinkedList.contains用法及代码示例
- Rust LinkedList.len用法及代码示例
- Rust LinkedList.append用法及代码示例
- Rust LinkedList用法及代码示例
- Rust LinkedList.push_back用法及代码示例
- Rust LinkedList.pop_back用法及代码示例
注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 Struct std::io::LineWriter。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。