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

转载于:https://www.cnblogs.com/gardenofhu/p/10151695.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值