use std::fs::OpenOptions;
use std::io::prelude::*;
use std::path::Path;
fn main() -> std::io::Result<()> {
let file_path = Path::new("hello.txt");
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(file_path)?;
file.write_all(b"Hello, World!\n")?;
println!("成功追加内容到文件: {}", file_path.display());
Ok(())
}
创建文件并且写入
fn read() -> Result<(), Box<dyn Error>> {
let file_path = Path::new("hello.txt");
match File::open(file_path) {
Ok(mut file) => {
let mut contents = String::new();
file.read_to_string(&mut contents)?;
println!("文件内容:\n{}", contents);
}
Err(e) => eprintln!("无法打开文件: {}", e),
}
Ok(())
}
读取文件