Core I/O traits and standard streams. BufReader wraps any Read for efficient buffered reading. io::Result<T> is used throughout.
Docs: doc.rust-lang.org
| Name | Signature | Description |
|---|---|---|
| io::stdin() | fn stdin() -> Stdin | Return handle to stdin |
| io::stdout() | fn stdout() -> Stdout | Return handle to stdout |
| io::stderr() | fn stderr() -> Stderr | Return handle to stderr |
| stdin.read_line | fn read_line(&self, buf: &mut String) -> Result<usize> | Read one line into String |
| stdin.lines() | fn lines(self) -> Lines<Self> | Iterator over lines from stdin |
| BufReader::new | fn new(inner: R) -> BufReader<R> | Create buffered reader |
| BufWriter::new | fn new(inner: W) -> BufWriter<W> | Create buffered writer |
| Read::read_to_string | fn read_to_string(&mut self, buf: &mut String) -> Result<usize> | Read all bytes as UTF-8 |
| Write::write_all | fn write_all(&mut self, buf: &[u8]) -> Result<()> | Write all bytes |
| Write::flush | fn flush(&mut self) -> Result<()> | Flush write buffer |
| BufRead::lines | fn lines(self) -> Lines<Self> | Iterator over lines |
| BufRead::read_line | fn read_line(&mut self, buf: &mut String) -> Result<usize> | Read line into buf |
| io::Error | struct Error | I/O error type |
| io::Result<T> | type Result<T> = Result<T, io::Error> | Alias for Result with io::Error |
| io::copy | fn copy(reader: &mut R, writer: &mut W) -> Result<u64> | Copy all bytes |
| io::Cursor | struct Cursor<T> | In-memory Read/Write/Seek over slice/Vec |
| io::empty() | fn empty() -> Empty | Reader that always returns EOF |
| io::sink() | fn sink() -> Sink | Writer that discards all data |
| writeln! | macro writeln!(writer, fmt, ...) | Write formatted line to writer |
| eprintln! | macro eprintln!(fmt, ...) | Print formatted line to stderr |
Save as main.rs in a Cargo project and run with cargo run.
use std::io::{self, BufRead, Write};
fn main() -> io::Result<()> {
let stdin = io::stdin();
let stdout = io::stdout();
let mut out = io::BufWriter::new(stdout.lock());
writeln!(out, "=== Line Echo (Ctrl-D to stop) ===")?;
for (i, line) in stdin.lock().lines().enumerate() {
let line = line?;
writeln!(out, "{:3}: {}", i + 1, line.to_uppercase())?;
}
// In-memory I/O with Cursor
use std::io::{Cursor, Read};
let data = b"Hello, Rust I/O!";
let mut cursor = Cursor::new(data);
let mut buf = String::new();
cursor.read_to_string(&mut buf)?;
writeln!(out, "Cursor: {}", buf)?;
out.flush()?;
Ok(())
}
// cargo run