用到了C++17的filesystem 库ios
说明:这个函数主要是用来处理日志中不一样Thread的日志,主要目的是将不一样Thread的日志写到不一样的文件中app
int GetThreadTime(const char * INPUT, const char * OutputFolder) { std::map<std::string, std::ofstream> mapWrite; std::filesystem::path pth(INPUT); if(exists(pth)) { std::cout << INPUT <<"文件存在\n"; } else { std::cout<< INPUT << "文件不存在\n"; return 0; } if (!std::filesystem::exists(OutputFolder)) { std::filesystem::create_directory(OutputFolder); } fstream fi(INPUT,ios_base::in); char buf[2048]{0}; std::string str; char paths[256]{0}; while (fi.getline(buf,sizeof(buf))) { str.clear(); str = buf; if (str.find("CalculateDownloadCostTime") != std::string::npos) //key value { std::string sthread; findThreadId(str,sthread); //获取Thread ID,string类型 long stattime,stoptime; int costtime; getStartTime(str,&stattime,&stoptime,&costtime); //获取日志行中的参数,本处是开始时间,结束事件,花费时间 auto result = mapWrite.find(sthread); if (result == mapWrite.end()) { sprintf_s(paths,sizeof(paths),"%s%s.txt",OutputFolder,sthread.c_str()); std::ofstream fo(paths,ios_base::app); fo << "threadid " << sthread << "XXXXXXX logs\n"; mapWrite.insert(std::pair<std::string, std::ofstream>(sthread,std::move(fo))); //注意:本处要么用std::move要么用shared_ptr,由于map须要为对象分配内存,并且ofstream也是uncopyable //http://coliru.stacked-crooked.com/a/c4486879ce9d4db0 //https://stackoverflow.com/questions/42920744/cant-we-manage-stdmapstring-ofstream } else { result->second << "threadid " << sthread << "XXXXXXX logs\n"; } } else { memset(buf,0,sizeof(buf)); continue; } memset(buf,0,sizeof(buf)); } for (auto& element : mapWrite) { element.second.close(); //批量释放句柄 } return 0; }