Rust Reference ยท Standard Library Modules
Rust BufReader and BufWriter types
Reference for std::io::BufReader and BufWriter: buffering small reads and writes, lines and read_line, flush and into_inner, LineWriter, stdout locking and drop behavior.
Every call to read or write on a File, TcpStream or similar handle may become a system call, which is slow if you do it for a few bytes at a time. std::io::BufReader<R> and std::io::BufWriter<W> wrap any reader or writer with an in-memory buffer (8 KiB by default) so that many small operations become a few large ones.
BufReader also provides the BufRead trait, which adds read_line, lines, read_until and split. Those are the usual way to read text line by line, and a bare File does not have them. Wrap Stdout in a BufWriter (or lock it) when printing a lot of output.
use std::io::{BufRead, BufReader}; let reader = BufReader::new(std::fs::File::open("data.txt")?); for line in reader.lines() { /* ... */ }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<R: Read> BufReader<R> { pub fn new(inner: R) -> BufReader<R>; pub fn with_capacity(capacity: usize, inner: R) -> BufReader<R>; pub fn buffer(&self) -> &[u8]; pub fn get_ref(&self) -> &R; pub fn get_mut(&mut self) -> &mut R; pub fn into_inner(self) -> R; } trait BufRead: Read { fn fill_buf(&mut self) -> io::Result<&[u8]>; fn consume(&mut self, amt: usize); fn read_line(&mut self, buf: &mut String) -> io::Result<usize>; fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize>; fn lines(self) -> Lines<Self>; fn split(self, byte: u8) -> Split<Self>; } impl<W: Write> BufWriter<W> { pub fn new(inner: W) -> BufWriter<W>; pub fn with_capacity(capacity: usize, inner: W) -> BufWriter<W>; pub fn buffer(&self) -> &[u8]; pub fn get_ref(&self) -> &W; pub fn into_inner(self) -> Result<W, IntoInnerError<BufWriter<W>>>; }
| Name | Description |
|---|---|
capacity |
Buffer size in bytes; default 8 KiB. A read larger than the buffer bypasses it. |
read_line |
Appends one line including its \n (and \r\n as is) to buf; returns bytes read, 0 at end of input. |
lines |
Iterator of io::Result<String> with the line ending removed. |
into_inner |
For BufWriter: flushes, then returns the wrapped writer. On failure the error returns the writer with its unwritten data. |
Errors and panics. read_line and lines return an InvalidData error when the bytes are not valid UTF-8. Nothing here panics; every I/O failure is an io::Error.
Usage notes
BufWriterflushes on drop, but any error during that final flush is ignored. When the output matters, callflush()yourself and check the result.- Do not mix direct reads on the inner reader with the buffered one: data already moved into the buffer is not visible to the inner handle. If you stop buffering, take
into_inner()and note that buffered bytes are lost. - Line-by-line input is fine without
BufReaderforStdin, becauseStdinis already buffered internally;stdin().lines()andread_lineexist directly (usestdin().lock()for speed). LineWriter<W>flushes after each newline.Stdoutuses it, which is whyprint!without a newline may not appear until a flush.- Binary data.
BufRead::fill_bufplusconsumelets you parse a stream without copying; it returns an empty slice at EOF. lines()allocates aStringper line. For maximum speed reuse one buffer withread_lineandclear(), as in the first example.- Memory. The buffer is allocated once at construction; a very large
with_capacityfor many readers adds up. - Seeking.
BufReader<R: Seek>implementsSeekand discards its buffer when you seek.