rust初体验之简单配置文件读取

简单实现ini、conf文件读取与解析缓存,可用于项目文件配置.

1.需要使用到全局变量用于项目缓存,导入如下库:

lazy_static = "1.4.0"

2.具体实现

#[macro_use]
extern crate lazy_static;

use std::io;
use std::fs::File;
use std::io::{BufReader, BufRead};
use std::collections::HashMap;
use std::sync::Mutex;

lazy_static! {
	// 此处表示声明全局可变 HashMap
    static ref MAP: Mutex<HashMap<String, String>> = Mutex::new(HashMap::new());
}

// 读取文件,path表示文件路径
fn read_file(path: &str) -> Result<i32, io::Error> {
	// 读取文件,失败直接返回Err
	let file: File = File::open(path)?;
	let buffered: BufReader<File> = BufReader::new(file);
 	// 存放`[key]`
    let mut key: String = "".to_string();
    // 缓存 : 去掉空格
    let mut new_line = "".to_string();
	
	for line in buffered.lines().map(|x| x.unwrap()) {
		new_line.clear();
        new_line.push_str(line.trim());
 		// 定义注释为`#`, 遇到注释跳过
 		 if line.contains("#") {
            continue;
        } else if line.contains("[") && line.contains("]") { // 解析`[key]`为`key::`
        	key.clear();
            new_line.pop();
            new_line.remove(0);
            key.push_str(new_line.as_str());
            key.push_str("::");
        } else if new_line.contains("=") { // 必须包含表达式, 才将值写入
            let kvs: Vec<&str> = new_line.as_str().split("=").collect::<Vec<&str>>();
            if kvs.len() == 2 { // 如果不满足则定义为异常数据,该数据暂不处理
                // 缓存
                let mut new_key: String = key.clone();
                new_key.push_str(kvs[0]);

                MAP.lock().unwrap().insert(new_key.trim().to_string(), kvs[1].trim().to_string());
            }
        }
	}
	return Ok(0);
}

fn main() {
	 // 这里只需要处理错误
    if let Err(e) = read_file("web/app.conf") {
        println!("err = {:?}", e);
    }

 	for (key, value) in MAP.lock().unwrap().iter() {
        println!("k = {}, y = {}", key, value);
    }
}
发布了6 篇原创文章 · 获赞 2 · 访问量 5610

猜你喜欢

转载自blog.csdn.net/u010766458/article/details/104579345