本文代码 https://github.com/tothis/rust-record/tree/main/cli/file-append-newline
Cargo.toml
[package]
name = "file-append-newline"
version = "0.1.0"
authors = ["Li Lei <this.lilei@gmail.com>"]
edition = "2021"
[dependencies]
toml = "0.5"
serde = { version = "1.0", features = ["derive"] }
once_cell = "1.8"
anyhow = "1.0"
config.toml
# 处理文件目录
path = "/Users/lilei/Downloads/test"
# 排除文件前缀
exclude_prefix = ["target"]
# 排除文件后缀
exclude_suffix = ["lock"]
src/config.rs
use std::fs;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Config {
pub path: String,
pub exclude_suffix: Vec<String>,
pub exclude_prefix: Vec<String>,
}
pub fn read_config() -> Config {
let str = fs::read_to_string("config.toml").unwrap();
toml::from_str(&str).unwrap()
}
src/main.rs
use std::fs;
use std::fs::OpenOptions;
use std::io::{Read, Write};
use once_cell::sync::Lazy;
mod config;
type Result<T = ()> = anyhow::Result<T>;
static CONFIG: Lazy<config::Config> = Lazy::new(|| {
config::read_config()
});
fn main() -> Result {
recursion(&CONFIG.path)?;
Ok(())
}
fn recursion(path: &str) -> Result {
// 排除前缀
for exclude_prefix in &CONFIG.exclude_prefix {
if path.starts_with(&(CONFIG.path.to_string() + "/" + &exclude_prefix)) {
return Ok(());
}
}
// 排除后缀
for exclude_suffix in &CONFIG.exclude_suffix {
if path.ends_with(exclude_suffix) {
return Ok(());
}
}
let file_type = fs::metadata(path)?.file_type();
let is_file = file_type.is_file();
let is_dir = file_type.is_dir();
// 递归目录
if is_dir {
for item in fs::read_dir(path)? {
recursion(item?.path().to_str().unwrap())?;
}
} else if is_file {
let mut file = OpenOptions::new().read(true).append(true).open(path)?;
let mut str = String::new();
file.read_to_string(&mut str)?;
if str.len() > 0 {
print!("{}", path);
let last_char = str.chars().last().unwrap();
if last_char != '\n' {
println!(" 已追加换行符");
write!(file, "\n")?;
} else {
println!();
}
}
}
Ok(())
}
测试
cargo run
————————————————
原文链接:https://blog.csdn.net/setlilei/article/details/118001396
如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!
txttool.com 说一段 esp56物联 查询128 IP查询