标准库 IO
学习目标
- 掌握
Read 和 Write trait
- 理解缓冲 IO
- 掌握标准输入输出
核心概念
Read trait
use std::io::Read;
fn read_all<R: Read>(reader: &mut R) -> std::io::Result<String> {
let mut buf = String::new();
reader.read_to_string(&mut buf)?;
Ok(buf)
}
fn main() -> std::io::Result<()> {
let data = b"hello world";
let mut cursor = std::io::Cursor::new(data);
let content = read_all(&mut cursor)?;
println!("{}", content);
Ok(())
}
Write trait
use std::io::Write;
fn main() -> std::io::Result<()> {
let mut buf = Vec::new();
buf.write_all(b"hello")?;
buf.write_all(b" world")?;
println!("{}", String::from_utf8_lossy(&buf));
std::io::stdout().write_all(b"stdout\n")?;
std::io::stderr().write_all(b"stderr\n")?;
Ok(())
}
BufRead trait
use std::io::{BufRead, BufReader};
fn main() -> std::io::Result<()> {
let data = b"line1\nline2\nline3";
let cursor = std::io::Cursor::new(data);
let reader = BufReader::new(cursor);
for line in reader.lines() {
println!("{}", line?);
}
Ok(())
}
标准输入
use std::io;
fn main() {
println!("请输入你的名字:");
let mut name = String::new();
io::stdin().read_line(&mut name).expect("读取失败");
println!("你好,{}!", name.trim());
}
Cursor
use std::io::{Cursor, Read, Seek, SeekFrom};
fn main() -> std::io::Result<()> {
let mut cursor = Cursor::new(vec![1, 2, 3, 4, 5]);
let mut buf = [0; 3];
cursor.read(&mut buf)?;
println!("{:?}", buf);
cursor.seek(SeekFrom::Start(0))?;
cursor.read(&mut buf)?;
println!("{:?}", buf);
Ok(())
}
小结
| Trait | 方法 | 说明 |
|---|
Read | read, read_to_string | 读取 |
Write | write, write_all | 写入 |
BufRead | lines, read_line | 缓冲读取 |
Cursor | 包装内存为 IO | 内存中读写 |