文件内容读取管理

来源:互联网 发布:新仙剑ol修改数据库 编辑:程序博客网 时间:2024/05/21 08:40

这个工具由下面两个文件组成:

头文件

#pragma once#ifndef _LocalFileRWManager_H_#define _LocalFileRWManager_H_#include <boost/thread/mutex.hpp>#include <string>#include <map>/*Title: 文件内容读取管理Purpose: 把常用的文件缓存在内存里,免得下次又要重新读一遍,主要用在编写http服务端程序中。Author: kagulaDate: 2016-12-28Environment:[1]VS2013 Update5Note:为了提高读文件速度,以后考虑不检查文件的最后修改时间。*/namespace kagula{struct LocalFileInfo{std::string content;unsigned long long timeStamp;};class LocalFileReadManager{public:bool getFileContent(const std::string &fullPath, std::string &content);protected:unsigned long long _sizeBuffer = 0;const unsigned long long _sizeMAXBuffer = 64 * 1024 * 1024;//64MBstd::map<std::string, LocalFileInfo> _mapFile;bool _getFileContent(const std::string &full_path, std::string &content);void addFile2Buffer(const std::string &full_path, const std::string &content,const long long timeStamp);boost::mutex _mutexRW;};}#endif


 

实现文件

#include "LocalFileReadManager.h"#include <boost/thread/locks.hpp>#include <istream>#include <fstream>#include <sys/types.h>#include <sys/stat.h>namespace kagula{bool GetFileInfo(const std::string &full_path, unsigned long long &fileSize, unsigned long long &timeStamp){struct stat buf;int result;result = stat(full_path.c_str(), &buf);if (result != 0)return false;fileSize = buf.st_size;timeStamp = buf.st_mtime;return true;}//functionbool LocalFileReadManager::getFileContent(const std::string &fullPath, std::string &content){unsigned long long fileSize;unsigned long long timeStamp;if (!GetFileInfo(fullPath, fileSize, timeStamp))return false;{boost::lock_guard<boost::mutex> l(_mutexRW);if (_mapFile.find(fullPath) != _mapFile.end()){if (timeStamp == _mapFile[fullPath].timeStamp){content = _mapFile[fullPath].content;return true;}//if}//if}content.clear();if (!_getFileContent(fullPath, content))return false;//Not cache big file.if (fileSize > _sizeMAXBuffer / 10)return true;addFile2Buffer(fullPath, content, timeStamp);return true;}//functionbool LocalFileReadManager::_getFileContent(const std::string &full_path, std::string &content){std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary);if (!is){return false;}//ifchar buf[4*1024];while (is.read(buf, sizeof(buf)).gcount() > 0)content.append(buf, is.gcount());return true;}//functionvoid LocalFileReadManager::addFile2Buffer(const std::string &full_path, const std::string &content, const long long timeStamp){boost::lock_guard<boost::mutex> l(_mutexRW);//while (_sizeBuffer + content.size() > _sizeMAXBuffer){std::map<std::string, LocalFileInfo>::iterator iter = _mapFile.begin();_sizeBuffer -= iter->second.content.size();_mapFile.erase(iter);}//while//_mapFile[full_path].content = content;_mapFile[full_path].timeStamp = timeStamp;_sizeBuffer += content.size();}//function}//namespace


 

0 0
原创粉丝点击