文件操作助手
在我们实现一个大型项目时,往往会有一个公共模块,这个公共模块是公用的,里面可能会包含文件操作助手、字符串操作助手、时间戳操作助手…
而我们今天就来实现一个文件操作助手,里面包含的功能有:
- 判断文件是否存在
- 获取文件大小
- 读文件
- 写文件
- 重命名
- 创建文件
- 删除文件
- 创建文件夹
- 删除文件夹
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;
};