Skip to content

Latest commit

 

History

History
97 lines (75 loc) · 2.23 KB

L08-IO.org

File metadata and controls

97 lines (75 loc) · 2.23 KB

CIS198 Lecture 8: I/O

读写的标准 Traits

trait Read/Write

  1. Read trait | link
  2. Write trait | link
  3. 返回值为 std::io::Result 而不是 std::Result
    type Result<T> = Result<T, std::io::Error>
        

读写示例

use std::io;
use std::io::prelude::*;
use std::fs::File;

fn main() -> io::Result<()> {
    let mut f = File::open("/tmp/foo.txt")?;
    let mut buffer = [0; 10];

    // read up to 10 bytes
    f.read(&mut buffer)?;
    println!("buffer1 = {buffer:?}");

    let s1: String = String::from_utf8(buffer.to_vec()).unwrap();
    println!("buffer2 = {s1:?}");

    Ok(())
}
buffer1 = [97, 97, 97, 32, 98, 98, 98, 32, 99, 99]
buffer2 = "aaa bbb cc"
use std::io;
use std::io::prelude::*;
use std::fs::File;

fn main() -> io::Result<()> {
    let mut buffer = File::create("/tmp/foo.out")?;
    write!(buffer, "Hello {}!", "Jack").unwrap();
    Ok(())
}

I/O 缓存

  1. BufReader
  2. BufWriter

Json

  1. Json 工具 | serde
cargo add serde --features derive
cargo add serde_json
cargo add serde_derive
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let point = Point { x: 1, y: 2 };

    // Convert the Point to a JSON string.
    let serialized = serde_json::to_string(&point).unwrap();

    // Prints serialized = {"x":1,"y":2}
    println!("serialized = {}", serialized);

    // Convert the JSON string back to a Point.
    let deserialized: Point = serde_json::from_str(&serialized).unwrap();

    // Prints deserialized = Point { x: 1, y: 2 }
    println!("deserialized = {:?}", deserialized);
}
error: Could not compile `cargow9PkJw`.