用到了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; }