70·标准库深入进阶

标准库 IO

标准库 IO

学习目标

  1. 掌握 ReadWrite trait
  2. 理解缓冲 IO
  3. 掌握标准输入输出

核心概念

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);  // [1, 2, 3]

    cursor.seek(SeekFrom::Start(0))?;
    cursor.read(&mut buf)?;
    println!("{:?}", buf);  // [1, 2, 3]

    Ok(())
}

小结

Trait方法说明
Readread, read_to_string读取
Writewrite, write_all写入
BufReadlines, read_line缓冲读取
Cursor包装内存为 IO内存中读写

练习编辑器

rust
Loading...