Category: rust
Categories
Rust 进程/线程处理
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(())
}
读取文件
Categories
Rust helloworld
基本命令
cargo new --bin helloworld
创建helloworld 项目项目为bin 可执行文件
cargo run
编译项目并且执行可执行文件
cargo build
编译项目