温馨提示×

IO操作

在Rust中,标准库提供了丰富的IO操作功能,包括文件读写、标准输入输出、网络操作等。下面是一些常用的IO操作示例:

  1. 文件读写:
use std::fs::File;
use std::io::{BufReader, BufRead, Read, Write};

fn main() {
    // 写文件
    let mut file = File::create("hello.txt").expect("create file failed");
    file.write_all(b"Hello, World!").expect("write file failed");
    
    // 读文件
    let file = File::open("hello.txt").expect("open file failed");
    let reader = BufReader::new(file);
    for line in reader.lines() {
        println!("{}", line.unwrap());
    }
}
  1. 标准输入输出:
use std::io;

fn main() {
    // 读取用户输入
    let mut input = String::new();
    println!("Please enter your name:");
    io::stdin().read_line(&mut input).expect("read line failed");
    println!("Hello, {}", input.trim());
    
    // 输出到控制台
    println!("Hello, World!");
}
  1. 网络操作:
use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};

fn main() {
    // 服务器
    let listener = TcpListener::bind("127.0.0.1:8080").expect("bind failed");
    for stream in listener.incoming() {
        match stream {
            Ok(mut stream) => {
                let mut buffer = [0; 1024];
                stream.read(&mut buffer).expect("read failed");
                println!("Received: {}", String::from_utf8_lossy(&buffer));
                stream.write_all(b"Hello, Client!").expect("write failed");
            }
            Err(e) => {
                eprintln!("Error: {}", e);
            }
        }
    }
    
    // 客户端
    let mut stream = TcpStream::connect("127.0.0.1:8080").expect("connect failed");
    stream.write_all(b"Hello, Server!").expect("write failed");
    let mut response = String::new();
    stream.read_to_string(&mut response).expect("read failed");
    println!("Received: {}", response);
}

以上是一些基础的IO操作示例,通过这些示例可以了解Rust标准库中的IO操作功能。在实际项目中,可以根据具体需求选择合适的IO操作方式。