解析一个如下的CONFIG文件
#config.txt #SHTTPD Web 服务器配置文件示例 #侦听端口 ListenPort = 80 #最大并发访问客户端数目 MaxClient = 8 #Web网页根目录 DocumentRoot = /home/www/ #CGI根目录 CGIRoot = /home/www/cgi-bin/ #默认访问文件名 DefaultFile = index.html #客户端空闲链接超时时间 TimeOut = 5
代码
#include <fstream> #include <string> #include <map> #include <iostream> #include <vector> #include <algorithm> #include <functional> #include <cctype> #include <locale> class GetConfigInfo { public: bool ReadFile(std::string fileName); private: std::map<std::string, std::string> configMap; std::fstream fin_; }; bool GetConfigInfo::ReadFile(std::string fileName) { fin_.open(fileName); if (fin_.bad()) return false; std::string readLine; while (getline(fin_, readLine)) //逐行读取,直到结束 { size_t i = readLine.find("#"); if (i != std::string::npos) continue; i = readLine.find_first_of(" \t"); while (i != std::string::npos) { readLine.erase(i,1); i = readLine.find_first_of(" \t"); } std::cout << readLine << std::endl; i = readLine.find("="); if (i == std::string::npos) continue; std::string s1 = readLine.substr(0,i); std::string s2 = readLine.substr(i + 1, std::string::npos); configMap.insert(std::pair<std::string, std::string>(s1, s2)); } fin_.close(); return true; } int main() { GetConfigInfo gci; gci.ReadFile("config.txt"); return 0; }