Buffered input and output
Quick answer
Buffered I/O groups small operations to reduce overhead on suitable devices. BufReader stores bytes read ahead, while BufWriter accumulates output before forwarding it. Buffering trades memory for potentially fewer device calls.
Read lines and flush writes
BufRead::lines yields Results containing UTF-8 lines without their LF or CRLF terminators. read_line instead appends to an existing String and includes the terminator if present. Explicitly flush buffered output when errors matter; a destructor cannot return a flush error. A flush is not necessarily durable storage synchronization.
use std::io::{self, BufRead, BufReader};fn main() -> io::Result<()> { let reader = BufReader::new(&b"one\n\ntwo\n"[..]); let mut count = 0; for line in reader.lines() { if !line?.is_empty() { count += 1; } } println!("{count}"); Ok(()) }Expected stdout (not executed):
2Empty lines are excluded after decoding.
use std::io::{self, BufWriter, Write};fn main() -> io::Result<()> { let mut bytes = Vec::new(); { let mut writer = BufWriter::new(&mut bytes); writer.write_all(b"record")?; writer.flush()?; } println!("{}", String::from_utf8(bytes).unwrap()); Ok(()) }Expected stdout (not executed):
recordThe writer's borrow ends before inspecting the destination.
Common mistake
Repeated read_line calls append unless you clear the String.
Try it yourself
Count lines containing a given word, and explain how invalid UTF-8 is reported.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Buffered input and output — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
You reuse one String with read_line. How can you prevent old lines accumulating?
Buffered input and output — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::io::{self, BufRead, BufReader}; fn main() -> io::Result<()> { let reader = BufReader::new(&b"one\n\ntwo\n"[..]); let mut count = 0; for line in reader.lines() { if !line?.is_empty() { count += 1; } } println!("{count}"); Ok(()) } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Buffered input and output — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::io::{self, BufWriter, Write}; fn main() -> io::Result<()> { let mut bytes = Vec::new(); { let mut writer = BufWriter::new(&mut bytes); writer.write_all(b"record")?; writer.flush()?; } println!("{}", String::from_utf8(bytes).unwrap()); Ok(()) } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.