1. 程式人生 > >C++ 批量開啟寫入檔案

C++ 批量開啟寫入檔案

用到了C++17的filesystem 庫

說明:這個函式主要是用來處理日誌中不同Thread的日誌,主要目的是將不同Thread的日誌寫到不同的檔案中

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;
}