在Rust中,你可以使用标准库中的std::fs模块来处理文件操作。以下是一些基本的文件操作示例:
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(())
}
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(())
}
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(())
}
use std::fs;
fn main() -> std::io::Result<()> {
fs::remove_file("hello.txt")?;
Ok(())
}
use std::fs;
fn main() -> std::io::Result<()> {
fs::rename("hello.txt", "hello_new.txt")?;
Ok(())
}
use std::fs;
fn main() -> std::io::Result<()> {
fs::create_dir("new_directory")?;
Ok(())
}
use std::fs;
fn main() -> std::io::Result<()> {
fs::remove_dir("new_directory")?;
Ok(())
}
这些示例展示了Rust中处理文件操作的基本方法。你可以根据自己的需求组合这些方法来实现更复杂的文件操作。