zoukankan      html  css  js  c++  java
  • 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 <<"文件存在
    ";
    	}
    	else
    	{
    		std::cout<< INPUT << "文件不存在
    ";
    		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
    ";
    				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
    ";
    			}
    
    		}
    		else
    		{
    			memset(buf,0,sizeof(buf));
    			continue;
    		}
    
    		memset(buf,0,sizeof(buf));
    	}
    	for (auto& element : mapWrite)
    	{
    		element.second.close();        //批量释放句柄
    	}
    	return 0;
    }
    
  • 相关阅读:
    手头上的几本关于实现程序设计语言的书
    Ubuntu 16.04 搭建KVM环境
    调用RESTful GET方法
    Ubuntu 16.04 安装Docker
    Ubuntu 16.04安装Java 8
    SecureCRT 多个会话显示在同一窗口
    Ubuntu 16.04 安装Maven3.3.9
    Python标准类型的分类
    Ubuntu 16.04 更改apt源
    LVM术语及相互关系
  • 原文地址:https://www.cnblogs.com/gardenofhu/p/10151695.html
Copyright © 2011-2022 走看看