温馨提示×

Rust在Linux中如何处理文件I/O

小樊
39
2025-11-24 14:55:24
栏目: 编程语言

在Linux中,Rust使用标准库中的std::fs模块和std::io模块来处理文件I/O。以下是一些基本的文件I/O操作:

  1. 打开文件:
use std::fs::File;
use std::io::{self, Read, Write};

fn main() -> io::Result<()> {
    let mut file = File::open("example.txt")?;
    // ...
}
  1. 读取文件内容:
use std::fs::File;
use std::io::{self, Read};

fn main() -> io::Result<()> {
    let mut file = File::open("example.txt")?;
    let mut contents = String::new();

    file.read_to_string(&mut contents)?;

    println!("File contents: {}", contents);
    Ok(())
}
  1. 写入文件内容:
use std::fs::File;
use std::io::{self, Write};

fn main() -> io::Result<()> {
    let mut file = File::create("example.txt")?;
    let contents = "Hello, world!";

    file.write_all(contents.as_bytes())?;

    Ok(())
}
  1. 追加内容到文件:
use std::fs::File;
use std::io::{self, Write};

fn main() -> io::Result<()> {
    let mut file = File::open("example.txt")?;
    let contents = "\nNew line!";

    file.write_all(contents.as_bytes())?;

    Ok(())
}
  1. 关闭文件:
use std::fs::File;
use std::io::{self, Write};

fn main() -> io::Result<()> {
    let mut file = File::create("example.txt")?;
    let contents = "Hello, world!";

    file.write_all(contents.as_bytes())?;
    drop(file); // 显式关闭文件

    Ok(())
}
  1. 使用缓冲区读写文件:
use std::fs::File;
use std::io::{self, BufRead, BufReader, BufWriter, Write};

fn main() -> io::Result<()> {
    let file = File::open("example.txt")?;
    let reader = BufReader::new(file);

    let file = File::create("output.txt")?;
    let mut writer = BufWriter::new(file);

    for line in reader.lines() {
        writeln!(writer, "{}", line?)?;
    }

    writer.flush()?; // 刷新缓冲区,将数据写入文件

    Ok(())
}

这些示例展示了如何在Rust中使用标准库进行基本的文件I/O操作。你可以根据自己的需求选择合适的方法。

0