當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Rust LineWriter用法及代碼示例


本文簡要介紹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-lang.org大神的英文原創作品 Struct std::io::LineWriter。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。