欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > 文件操作助手

文件操作助手

2025/3/29 18:33:53 来源:https://blog.csdn.net/weixin_74006549/article/details/146463525  浏览:    关键词:文件操作助手

文件操作助手

在我们实现一个大型项目时,往往会有一个公共模块,这个公共模块是公用的,里面可能会包含文件操作助手、字符串操作助手、时间戳操作助手…

而我们今天就来实现一个文件操作助手,里面包含的功能有:

  • 判断文件是否存在
  • 获取文件大小
  • 读文件
  • 写文件
  • 重命名
  • 创建文件
  • 删除文件
  • 创建文件夹
  • 删除文件夹
class FileHelper
{public:FileHelper(const std::string& filename):_filename(filename){}bool exists(){struct stat st;return (stat(_filename.c_str(),&st) == 0);}size_t size(){struct stat st;int ret = stat(_filename.c_str(),&st);if(ret < 0)return ret;return st.st_size;}bool read(char* body,size_t offset,size_t len){//打开文件std::ifstream in(_filename,std::ios::binary | std::ios::in);if(!in.is_open()){ELOG("%s 打开文件失败!",_filename.c_str());return false;}//跳转到读取位置in.seekg(offset,std::ios::beg);//读取数据in.read(body,len);if(in.good() == false){ELOG("%s 读取文件失败!",_filename.c_str());in.close();return false;}in.close();return true;//关闭文件}bool read(std::string& body){size_t fsize = this->size();body.resize(fsize);return read(&body[0],0,fsize);}bool write(const char *body,size_t offset,size_t len){//打开文件std::fstream fs(_filename,std::ios::binary | std::ios::in | std::ios::out);if(!fs.is_open()){ELOG("%s 打开文件失败!",_filename.c_str());return false;}//跳转到读取位置fs.seekp(offset,std::ios::beg);//读取数据fs.write(body,len);if(fs.good() == false){ELOG("%s 读取文件失败!",_filename.c_str());fs.close();return false;} fs.close();return true;//关闭文件}bool write(const std::string& body){return write(body.c_str(),0,body.size());}static std::string parentDirectory(const std::string& filename){size_t pos = filename.find_last_of('/');if(pos == std::string::npos)return ".";return filename.substr(0,pos);}bool rename(const std::string& newname){return (::rename(_filename.c_str(),newname.c_str()) == 0);}static bool createFile(const std::string &filename) {std::fstream ofs(filename, std::ios::binary | std::ios::out); if (ofs.is_open() == false) {ELOG("%s 文件打开失败!", filename.c_str());return false;}ofs.close();return true;}static bool removeFile(const std::string &filename) {return (::remove(filename.c_str()) == 0);}static bool createDirectory(const std::string &path) {//  aaa/bbb/ccc    cccc// 在多级路径创建中,我们需要从第一个父级目录开始创建size_t pos, idx = 0;while(idx < path.size()) {pos = path.find("/", idx);if (pos == std::string::npos) {return (mkdir(path.c_str(), 0775) == 0);}std::string subpath = path.substr(0, pos);int ret = mkdir(subpath.c_str(), 0775);if (ret != 0 && errno != EEXIST) {ELOG("创建目录 %s 失败: %s", subpath.c_str(), strerror(errno));return false;}idx = pos + 1;}return true;}static bool removeDirectory(const std::string &path) {// rm -rf path// system()std::string cmd = "rm -rf " + path;return (system(cmd.c_str()) != -1);}private:std::string _filename;
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词