std::io
最後更新
提供讀寫資料的共通介面:不管資料來自檔案、網路、記憶體還是終端機,都用同一組特徵(trait)處理。
這個模組做什麼
程式常常要「讀進一串位元組、處理後寫出去」。
std::io 把這件事抽象成兩個核心特徵:Read:可以從中讀出位元組的東西(檔案、TCP 連線、&[u8]、標準輸入)Write:可以寫入位元組的東西(檔案、Vec<u8>、標準輸出)
只要實作了這兩個特徵,就能套用同一套工具:緩衝、逐行讀取、整段複製,就像電器都用同一種插座。
| 需求 | 用什麼 |
|---|---|
| 讀出位元組或整段文字 | Read |
| 寫入位元組、格式化輸出 | Write、write! |
| 逐行讀取 | BufRead(搭配 BufReader) |
| 減少系統呼叫次數 | BufReader/BufWriter |
| 終端機輸入輸出 | stdin()/stdout()/stderr() |
| 在記憶體裡模擬檔案 | Cursor |
| 把讀端的內容全倒到寫端 | io::copy |
開檔見 std::fs、網路連線見 std::net,它們的物件都實作
Read/Write。匯入
- use std::io::{self, BufRead, BufReader, BufWriter, Read, Write};
Read、Write、BufRead 不在 prelude 裡,呼叫它們的方法前必須先 use 對應特徵,否則編譯器會說找不到方法。常用 API
Read:讀出位元組
Read 只要求實作 read:把資料讀進你給的緩衝區,回傳讀到幾個位元組;回傳 0 代表讀完(EOF,end of file)。read_to_string、read_to_end、read_exact 都是建立在它之上的預設方法。&[u8] 也實作了 Read,每讀一次切片就往前縮。簽名:
- pub trait Read {
- fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
- fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize>;
- }
注意:
read 一次不保證填滿緩衝區,讀到的數量可能比緩衝區小;需要「剛好讀滿 N 個位元組」時用 read_exact,資料不夠會回傳 ErrorKind::UnexpectedEof。read_to_string 遇到非 UTF-8 資料會回傳 ErrorKind::InvalidData。範例:
- use std::io::Read;
- fn main() -> std::io::Result<()> {
- let mut source: &[u8] = b"hello, reader";
- let mut first = [0u8; 5];
- let n = source.read(&mut first)?;
- println!("read {} bytes: {:?}", n, std::str::from_utf8(&first[..n]).unwrap());
- let mut rest = String::new();
- source.read_to_string(&mut rest)?;
- println!("rest: {:?}", rest);
- Ok(())
- }
輸出:
- read 5 bytes: "hello"
- rest: ", reader"
Write:寫入位元組與格式化
Write 的核心方法是 write 和 flush。日常幾乎都用 write_all(保證全部寫完),以及 write!/writeln! 巨集(macro),它們和 println! 一樣支援格式化,只是目標換成任何實作 Write 的東西。Vec<u8> 實作了 Write,寫入的內容會附加在尾端。簽名:
- pub trait Write {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize>;
- fn flush(&mut self) -> io::Result<()>;
- fn write_all(&mut self, buf: &[u8]) -> io::Result<()>;
- }
注意:
write 可能只寫入部分資料,一般請用 write_all。write! 回傳 io::Result<()>,忽略它會有未使用 Result 的警告。範例:
- use std::io::Write;
- fn main() -> std::io::Result<()> {
- let mut buf: Vec<u8> = Vec::new();
- buf.write_all(b"id,name\n")?;
- write!(buf, "{},{}\n", 1, "Alice")?;
- writeln!(buf, "{},{}", 2, "Bob")?;
- buf.flush()?;
- print!("{}", String::from_utf8(buf).unwrap());
- Ok(())
- }
輸出:
- id,name
- 1,Alice
- 2,Bob
BufRead:逐行讀取
BufRead 是「帶有內部緩衝區的 Read」。有了緩衝區,才能有效率地找換行字元,所以 lines、read_line、split 這類方法都在 BufRead 上。&[u8] 與 BufReader 都實作了它。lines() 的每一行已去掉結尾的 \n(及 \r\n),項目型別是 io::Result<String>。範例中的 split 寫成 BufRead::split(...),因為切片本身也有同名的 split 方法,直接呼叫會選到切片版本。簽名:
- pub trait BufRead: Read {
- fn read_line(&mut self, buf: &mut String) -> io::Result<usize>;
- fn lines(self) -> Lines<Self>;
- fn split(self, byte: u8) -> Split<Self>;
- }
範例:
- use std::io::BufRead;
- fn main() -> std::io::Result<()> {
- let data: &[u8] = b"apple\nbanana\n\ncherry";
- for (i, line) in data.lines().enumerate() {
- let line = line?;
- println!("{}: {:?}", i, line);
- }
- let fields: &[u8] = b"a-b-c";
- let words: Vec<Vec<u8>> = BufRead::split(fields, b'-').collect::<Result<_, _>>()?;
- println!("split count: {}", words.len());
- Ok(())
- }
輸出:
- 0: "apple"
- 1: "banana"
- 2: ""
- 3: "cherry"
- split count: 3
BufReader:替讀取加上緩衝
對檔案或網路連線直接
read,每次都是一次系統呼叫。BufReader 一次讀進一大塊(預設 8 KiB),之後的小讀取都從記憶體拿;它也讓任何 Read 變成 BufRead,於是能逐行讀。read_line 會把整行(包含 \n)附加到字串後面,回傳讀到的位元組數;回傳 0 代表讀完了。簽名:
- pub fn new(inner: R) -> BufReader<R>;
注意:
read_line 是附加而不是覆蓋,重複使用同一個 String 時要先 clear(),否則內容會一直累積。範例:
- use std::io::{BufRead, BufReader};
- fn main() -> std::io::Result<()> {
- let raw: &[u8] = b"first line\nsecond line\n";
- let mut reader = BufReader::new(raw);
- let mut line = String::new();
- let n = reader.read_line(&mut line)?;
- println!("{} bytes: {:?}", n, line);
- line.clear();
- reader.read_line(&mut line)?;
- println!("trimmed: {:?}", line.trim_end());
- line.clear();
- let n = reader.read_line(&mut line)?;
- println!("at end: {}", n);
- Ok(())
- }
輸出:
- 11 bytes: "first line\n"
- trimmed: "second line"
- at end: 0
BufWriter:替寫入加上緩衝
BufWriter 把小寫入累積在記憶體,滿了或 flush 時才一次寫出。大量輸出時用它包住 stdout().lock() 能明顯加速。範例中 buffer() 顯示 flush 前還有多少位元組尚未輸出。簽名:
- pub fn new(inner: W) -> BufWriter<W>;
- pub fn buffer(&self) -> &[u8];
注意:
BufWriter 被丟棄(drop)時會嘗試 flush,但這時發生的錯誤會被默默忽略。重要資料請明確呼叫 flush()?,才能拿到錯誤。範例:
- use std::io::{self, BufWriter, Write};
- fn main() -> io::Result<()> {
- let stdout = io::stdout();
- let mut out = BufWriter::new(stdout.lock());
- for i in 1..=3 {
- writeln!(out, "row {}", i)?;
- }
- let pending = out.buffer().len();
- let cap = out.capacity();
- out.flush()?;
- drop(out);
- println!("pending before flush: {} bytes, capacity: {}", pending, cap);
- Ok(())
- }
輸出:
- row 1
- row 2
- row 3
- pending before flush: 18 bytes, capacity: 8192
stdin 與 stdout:終端機輸入輸出
io::stdin()/stdout()/stderr() 回傳標準輸入、輸出、錯誤的控制代碼(handle)。它們由所有執行緒共用,每次操作都要上鎖;先 .lock() 取得鎖,連續讀寫就不必重複上鎖。stdin().lock() 實作 BufRead,可直接 lines()。下面的範例逐行讀入數字並加總。執行時以管線餵入輸入:
printf '10\n20\nabc\n12\n' | ./main。簽名:
- pub fn stdin() -> Stdin;
- pub fn stdout() -> Stdout;
- pub fn lock(&self) -> StdinLock<'static>;
注意:
print!(不換行)的內容可能留在緩衝區,要在讀取使用者輸入前顯示提示文字,記得先呼叫 io::stdout().flush()。範例:
- use std::io::{self, BufRead, Write};
- fn main() -> io::Result<()> {
- let stdin = io::stdin();
- let mut total = 0;
- for line in stdin.lock().lines() {
- let line = line?;
- if let Ok(n) = line.trim().parse::<i32>() {
- total += n;
- }
- }
- let mut out = io::stdout().lock();
- writeln!(out, "total = {}", total)?;
- Ok(())
- }
輸出:
- total = 42
Cursor:在記憶體裡模擬檔案
Cursor<T> 包住一塊記憶體(Vec<u8>、&[u8] 等)並記住讀寫位置,提供 Read、Write、Seek。原本讀寫檔案的函式改傳 Cursor,就能在記憶體中測試。Seek 負責移動位置,SeekFrom::Start(n) 指從開頭算第 n 個位元組;寫入會覆蓋原有內容。簽名:
- pub fn new(inner: T) -> Cursor<T>;
- pub fn set_position(&mut self, pos: u64);
範例:
- use std::io::{Cursor, Read, Seek, SeekFrom, Write};
- fn main() -> std::io::Result<()> {
- let mut cur = Cursor::new(Vec::new());
- cur.write_all(b"Hello World")?;
- println!("position after write: {}", cur.position());
- cur.seek(SeekFrom::Start(6))?;
- cur.write_all(b"Rust!")?;
- cur.set_position(0);
- let mut s = String::new();
- cur.read_to_string(&mut s)?;
- println!("{}", s);
- Ok(())
- }
輸出:
- position after write: 11
- Hello Rust!
io::Error 與 ErrorKind:判斷錯誤種類
I/O 操作都回傳
io::Result<T>(Result<T, io::Error> 的別名)。kind() 回傳 ErrorKind 列舉,用來分辨「檔案不存在」「權限不足」「資料格式錯誤」,不必比對訊息文字。自己產生錯誤時用
io::Error::new(kind, 訊息);種類不重要時用 io::Error::other(訊息)(Rust 1.74 起)。Result 與 ? 的基本用法見 std::result,自訂錯誤型別見 std::error。簽名:
- pub type Result<T> = result::Result<T, io::Error>;
- pub fn new<E>(kind: ErrorKind, error: E) -> Error;
- pub fn kind(&self) -> ErrorKind;
注意:
ErrorKind 標有 #[non_exhaustive],未來可能新增成員,match 時一定要保留 _ 分支。範例:
- use std::fs::File;
- use std::io::{self, ErrorKind};
- fn parse_port(s: &str) -> io::Result<u16> {
- s.parse::<u16>()
- .map_err(|e| io::Error::new(ErrorKind::InvalidInput, format!("bad port {:?}: {}", s, e)))
- }
- fn main() {
- match File::open("no-such-file-for-io-demo.txt") {
- Ok(_) => println!("opened"),
- Err(e) if e.kind() == ErrorKind::NotFound => println!("kind: {:?}", e.kind()),
- Err(e) => println!("other error: {}", e),
- }
- match parse_port("99999") {
- Ok(p) => println!("port {}", p),
- Err(e) => println!("{:?}: {}", e.kind(), e),
- }
- let custom = io::Error::other("disk quota reached");
- println!("{:?}: {}", custom.kind(), custom);
- }
輸出:
- kind: NotFound
- InvalidInput: bad port "99999": number too large to fit in target type
- Other: disk quota reached
io::copy:把讀端整個倒到寫端
io::copy 不斷從 reader 讀、往 writer 寫直到讀完,回傳複製的位元組數。轉存資料流、把檔案內容輸出到終端機都能一行完成。簽名:
- pub fn copy<R, W>(reader: &mut R, writer: &mut W) -> io::Result<u64>
- where R: Read + ?Sized, W: Write + ?Sized;
範例:
- use std::io::{self, Cursor};
- fn main() -> io::Result<()> {
- let mut src = Cursor::new("copy me, all of me\n");
- let n = io::copy(&mut src, &mut io::stdout())?;
- println!("copied {} bytes", n);
- Ok(())
- }
輸出:
- copy me, all of me
- copied 19 bytes
重點整理
Read/Write是 I/O 的共通介面;使用它們的方法前要use std::io::{Read, Write}- 寫入用
write_all或write!,不要只用write;讀取要剛好 N 位元組用read_exact - 逐行讀取靠
BufRead::lines(),任何Read包進BufReader就能用 - 大量輸出用
BufWriter,結束前明確flush()?才拿得到錯誤 - 用
e.kind()判斷錯誤種類,match要留_分支 Cursor讓記憶體假裝成檔案,方便測試讀寫邏輯