加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
util.hpp 3.51 KB
一键复制 编辑 原始数据 按行查看 历史
刘枭雄 提交于 2022-04-02 16:05 . first version
#ifndef __MY_UTIL__
#define __MY_UTIL__
#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
#include<time.h>
#include<fstream>
#include<sys/stat.h>
#include<experimental/filesystem>
namespace fs = std::experimental::filesystem;
namespace cloud
{
class FileUtil
{
private:
std::string _name;
public:
FileUtil(const std::string &name):_name(name)
{
}
std::string Name()
{
return fs::path(_name).filename().string();
}
bool Exists()
{
return fs::exists(_name);
}
size_t Size()
{
if(this->Exists() == false)
{
return 0;
}
return fs::file_size(_name);
}
time_t MTime()
{
if(this->Exists() == false)
{
return 0;
}
auto ftime = fs::last_write_time(_name);
std::time_t cftime = decltype(ftime)::clock::to_time_t(ftime);
return cftime;
}
time_t ATime()
{
if(this->Exists() == false)
{
return 0;
}
struct stat st;
stat(_name.c_str(),&st);
return st.st_atime;
}
bool Read(std::string *body)
{
if(this->Exists()==false)
{
return false;
}
std::ifstream ifs;
ifs.open(_name,std::ios::binary);
if(ifs.is_open() == false)
{
std::cout<<"read open failed"<<std::endl;
return false;
}
size_t fsize = this->Size();
body->resize(fsize);
ifs.read(&(*body)[0],fsize);
if(ifs.good()==false)
{
std::cout<<"read file failed"<<std::endl;
ifs.close();
return false;
}
ifs.close();
return true;
}
bool Write(const std::string &body)
{
std::ofstream ofs;
ofs.open(_name,std::ios::binary);
if(ofs.is_open() == false)
{
std::cout<<"write open failed"<<std::endl;
return false;
}
ofs.write(body.c_str(),body.size());
if(ofs.good()==false)
{
std::cout<<"write file failed"<<std::endl;
ofs.close();
return false;
}
ofs.close();
return true;
}
bool MCreateDirectory()
{
if(this->Exists())
{
return true;
}
fs::create_directories(_name);
return true;
}
bool ScanDirectory(std::vector<std::string> *arry)
{
if(this->Exists()==false)
{
return false;
}
for(auto &a : fs::directory_iterator(_name))
{
if(fs::is_directory(a) == true)
{
continue;
}
std::string pathname = fs::path(a).relative_path().string();
arry->push_back(pathname);
}
return true;
}
bool Remove()
{
if(this->Exists())
{
return true;
}
fs::remove_all(_name);
return true;
}
};
}
#endif
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化