温馨提示×

Linux中Rust如何处理文件操作

小樊
56
2025-08-17 11:22:55
栏目: 编程语言

在Rust中,你可以使用标准库中的std::fs模块来处理文件操作。以下是一些基本的文件操作示例:

  1. 创建一个新文件:
use std::fs::File;
use std::io::Write;

fn main() -> std::io::Result<()> {
    let mut file = File::create("hello.txt")?;
    file.write_all(b"Hello, world!")?;
    Ok(())
}
  1. 打开一个现有文件:
use std::fs::File;
use std::io::{self, Read};

fn main() -> io::Result<()> {
    let mut file = File::open("hello.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::Write;

fn main() -> std::io::Result<()> {
    let mut file = File::open("hello.txt")?;
    file.write_all(b"\nAppended text")?;
    Ok(())
}
  1. 删除一个文件:
use std::fs;

fn main() -> std::io::Result<()> {
    fs::remove_file("hello.txt")?;
    Ok(())
}
  1. 重命名一个文件:
use std::fs;

fn main() -> std::io::Result<()> {
    fs::rename("hello.txt", "hello_new.txt")?;
    Ok(())
}
  1. 创建目录:
use std::fs;

fn main() -> std::io::Result<()> {
    fs::create_dir("new_directory")?;
    Ok(())
}
  1. 删除目录:
use std::fs;

fn main() -> std::io::Result<()> {
    fs::remove_dir("new_directory")?;
    Ok(())
}

这些示例展示了Rust中处理文件操作的基本方法。你可以根据自己的需求组合这些方法来实现更复杂的文件操作。

0