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。

匯入


  1. 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,每讀一次切片就往前縮。
簽名:
  1. pub trait Read {
  2. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
  3. fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize>;
  4. }

注意:read 一次不保證填滿緩衝區,讀到的數量可能比緩衝區小;需要「剛好讀滿 N 個位元組」時用 read_exact,資料不夠會回傳 ErrorKind::UnexpectedEof。read_to_string 遇到非 UTF-8 資料會回傳 ErrorKind::InvalidData。
範例:
  1. use std::io::Read;
  2. fn main() -> std::io::Result<()> {
  3. let mut source: &[u8] = b"hello, reader";
  4. let mut first = [0u8; 5];
  5. let n = source.read(&mut first)?;
  6. println!("read {} bytes: {:?}", n, std::str::from_utf8(&first[..n]).unwrap());
  7. let mut rest = String::new();
  8. source.read_to_string(&mut rest)?;
  9. println!("rest: {:?}", rest);
  10. Ok(())
  11. }

輸出:
  1. read 5 bytes: "hello"
  2. rest: ", reader"

Write:寫入位元組與格式化


Write 的核心方法是 write 和 flush。日常幾乎都用 write_all(保證全部寫完),以及 write!/writeln! 巨集(macro),它們和 println! 一樣支援格式化,只是目標換成任何實作 Write 的東西。
Vec<u8> 實作了 Write,寫入的內容會附加在尾端。
簽名:
  1. pub trait Write {
  2. fn write(&mut self, buf: &[u8]) -> io::Result<usize>;
  3. fn flush(&mut self) -> io::Result<()>;
  4. fn write_all(&mut self, buf: &[u8]) -> io::Result<()>;
  5. }

注意:write 可能只寫入部分資料,一般請用 write_all。write! 回傳 io::Result<()>,忽略它會有未使用 Result 的警告。
範例:
  1. use std::io::Write;
  2. fn main() -> std::io::Result<()> {
  3. let mut buf: Vec<u8> = Vec::new();
  4. buf.write_all(b"id,name\n")?;
  5. write!(buf, "{},{}\n", 1, "Alice")?;
  6. writeln!(buf, "{},{}", 2, "Bob")?;
  7. buf.flush()?;
  8. print!("{}", String::from_utf8(buf).unwrap());
  9. Ok(())
  10. }

輸出:
  1. id,name
  2. 1,Alice
  3. 2,Bob

BufRead:逐行讀取


BufRead 是「帶有內部緩衝區的 Read」。有了緩衝區,才能有效率地找換行字元,所以 lines、read_line、split 這類方法都在 BufRead 上。&[u8] 與 BufReader 都實作了它。
lines() 的每一行已去掉結尾的 \n(及 \r\n),項目型別是 io::Result<String>。範例中的 split 寫成 BufRead::split(...),因為切片本身也有同名的 split 方法,直接呼叫會選到切片版本。
簽名:
  1. pub trait BufRead: Read {
  2. fn read_line(&mut self, buf: &mut String) -> io::Result<usize>;
  3. fn lines(self) -> Lines<Self>;
  4. fn split(self, byte: u8) -> Split<Self>;
  5. }

範例:
  1. use std::io::BufRead;
  2. fn main() -> std::io::Result<()> {
  3. let data: &[u8] = b"apple\nbanana\n\ncherry";
  4. for (i, line) in data.lines().enumerate() {
  5. let line = line?;
  6. println!("{}: {:?}", i, line);
  7. }
  8. let fields: &[u8] = b"a-b-c";
  9. let words: Vec<Vec<u8>> = BufRead::split(fields, b'-').collect::<Result<_, _>>()?;
  10. println!("split count: {}", words.len());
  11. Ok(())
  12. }

輸出:
  1. 0: "apple"
  2. 1: "banana"
  3. 2: ""
  4. 3: "cherry"
  5. split count: 3

BufReader:替讀取加上緩衝


對檔案或網路連線直接 read,每次都是一次系統呼叫。BufReader 一次讀進一大塊(預設 8 KiB),之後的小讀取都從記憶體拿;它也讓任何 Read 變成 BufRead,於是能逐行讀。
read_line 會把整行(包含 \n)附加到字串後面,回傳讀到的位元組數;回傳 0 代表讀完了。
簽名:
  1. pub fn new(inner: R) -> BufReader<R>;

注意:read_line 是附加而不是覆蓋,重複使用同一個 String 時要先 clear(),否則內容會一直累積。
範例:
  1. use std::io::{BufRead, BufReader};
  2. fn main() -> std::io::Result<()> {
  3. let raw: &[u8] = b"first line\nsecond line\n";
  4. let mut reader = BufReader::new(raw);
  5. let mut line = String::new();
  6. let n = reader.read_line(&mut line)?;
  7. println!("{} bytes: {:?}", n, line);
  8. line.clear();
  9. reader.read_line(&mut line)?;
  10. println!("trimmed: {:?}", line.trim_end());
  11. line.clear();
  12. let n = reader.read_line(&mut line)?;
  13. println!("at end: {}", n);
  14. Ok(())
  15. }

輸出:
  1. 11 bytes: "first line\n"
  2. trimmed: "second line"
  3. at end: 0

BufWriter:替寫入加上緩衝


BufWriter 把小寫入累積在記憶體,滿了或 flush 時才一次寫出。大量輸出時用它包住 stdout().lock() 能明顯加速。範例中 buffer() 顯示 flush 前還有多少位元組尚未輸出。
簽名:
  1. pub fn new(inner: W) -> BufWriter<W>;
  2. pub fn buffer(&self) -> &[u8];

注意:BufWriter 被丟棄(drop)時會嘗試 flush,但這時發生的錯誤會被默默忽略。重要資料請明確呼叫 flush()?,才能拿到錯誤。
範例:
  1. use std::io::{self, BufWriter, Write};
  2. fn main() -> io::Result<()> {
  3. let stdout = io::stdout();
  4. let mut out = BufWriter::new(stdout.lock());
  5. for i in 1..=3 {
  6. writeln!(out, "row {}", i)?;
  7. }
  8. let pending = out.buffer().len();
  9. let cap = out.capacity();
  10. out.flush()?;
  11. drop(out);
  12. println!("pending before flush: {} bytes, capacity: {}", pending, cap);
  13. Ok(())
  14. }

輸出:
  1. row 1
  2. row 2
  3. row 3
  4. 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。
簽名:
  1. pub fn stdin() -> Stdin;
  2. pub fn stdout() -> Stdout;
  3. pub fn lock(&self) -> StdinLock<'static>;

注意:print!(不換行)的內容可能留在緩衝區,要在讀取使用者輸入前顯示提示文字,記得先呼叫 io::stdout().flush()。
範例:
  1. use std::io::{self, BufRead, Write};
  2. fn main() -> io::Result<()> {
  3. let stdin = io::stdin();
  4. let mut total = 0;
  5. for line in stdin.lock().lines() {
  6. let line = line?;
  7. if let Ok(n) = line.trim().parse::<i32>() {
  8. total += n;
  9. }
  10. }
  11. let mut out = io::stdout().lock();
  12. writeln!(out, "total = {}", total)?;
  13. Ok(())
  14. }

輸出:
  1. total = 42

Cursor:在記憶體裡模擬檔案


Cursor<T> 包住一塊記憶體(Vec<u8>、&[u8] 等)並記住讀寫位置,提供 Read、Write、Seek。原本讀寫檔案的函式改傳 Cursor,就能在記憶體中測試。
Seek 負責移動位置,SeekFrom::Start(n) 指從開頭算第 n 個位元組;寫入會覆蓋原有內容。
簽名:
  1. pub fn new(inner: T) -> Cursor<T>;
  2. pub fn set_position(&mut self, pos: u64);

範例:
  1. use std::io::{Cursor, Read, Seek, SeekFrom, Write};
  2. fn main() -> std::io::Result<()> {
  3. let mut cur = Cursor::new(Vec::new());
  4. cur.write_all(b"Hello World")?;
  5. println!("position after write: {}", cur.position());
  6. cur.seek(SeekFrom::Start(6))?;
  7. cur.write_all(b"Rust!")?;
  8. cur.set_position(0);
  9. let mut s = String::new();
  10. cur.read_to_string(&mut s)?;
  11. println!("{}", s);
  12. Ok(())
  13. }

輸出:
  1. position after write: 11
  2. 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。
簽名:
  1. pub type Result<T> = result::Result<T, io::Error>;
  2. pub fn new<E>(kind: ErrorKind, error: E) -> Error;
  3. pub fn kind(&self) -> ErrorKind;

注意:ErrorKind 標有 #[non_exhaustive],未來可能新增成員,match 時一定要保留 _ 分支。
範例:
  1. use std::fs::File;
  2. use std::io::{self, ErrorKind};
  3. fn parse_port(s: &str) -> io::Result<u16> {
  4. s.parse::<u16>()
  5. .map_err(|e| io::Error::new(ErrorKind::InvalidInput, format!("bad port {:?}: {}", s, e)))
  6. }
  7. fn main() {
  8. match File::open("no-such-file-for-io-demo.txt") {
  9. Ok(_) => println!("opened"),
  10. Err(e) if e.kind() == ErrorKind::NotFound => println!("kind: {:?}", e.kind()),
  11. Err(e) => println!("other error: {}", e),
  12. }
  13. match parse_port("99999") {
  14. Ok(p) => println!("port {}", p),
  15. Err(e) => println!("{:?}: {}", e.kind(), e),
  16. }
  17. let custom = io::Error::other("disk quota reached");
  18. println!("{:?}: {}", custom.kind(), custom);
  19. }

輸出:
  1. kind: NotFound
  2. InvalidInput: bad port "99999": number too large to fit in target type
  3. Other: disk quota reached

io::copy:把讀端整個倒到寫端


io::copy 不斷從 reader 讀、往 writer 寫直到讀完,回傳複製的位元組數。轉存資料流、把檔案內容輸出到終端機都能一行完成。
簽名:
  1. pub fn copy<R, W>(reader: &mut R, writer: &mut W) -> io::Result<u64>
  2. where R: Read + ?Sized, W: Write + ?Sized;

範例:
  1. use std::io::{self, Cursor};
  2. fn main() -> io::Result<()> {
  3. let mut src = Cursor::new("copy me, all of me\n");
  4. let n = io::copy(&mut src, &mut io::stdout())?;
  5. println!("copied {} bytes", n);
  6. Ok(())
  7. }

輸出:
  1. copy me, all of me
  2. 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 讓記憶體假裝成檔案,方便測試讀寫邏輯