util.hpp
#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sys/stat.h>
#include <unistd.h>
#include <cstring>
#include <cstdint>
#include <experimental/filesystem>
#include <jsoncpp/json/json.h>
#include <memory>
#include "bundle.h"
namespace cloud
{
namespace fs = std::experimental::filesystem;
class fileUtil
{
public:
fileUtil(std::string filename)
:_filename(filename)
{
}
bool Remove()
{
if(exists() == false)
{
return true;
}
remove(_filename.c_str());
return true;
}
size_t fileSize()
{
struct stat st;
int ret = stat(_filename.c_str(), &st);
if(ret == -1)
{
std::cout << strerror(errno) << std::endl;
return 0;
}
return st.st_size;
}
time_t lastModifyTime()
{
struct stat st;
int ret = stat(_filename.c_str(), &st);
if(ret == -1)
{
std::cout << strerror(errno) << std::endl;
return -1;
}
return st.st_mtime;
}
time_t lastAccessTime()
{
struct stat st;
int ret = stat(_filename.c_str(), &st);
if(ret == -1)
{
std::cout << strerror(errno) << std::endl;
return -1;
}
return st.st_atime;
}
std::string fileName()
{
size_t pos = _filename.find_last_of("/");
if(pos == std::string::npos)
{
return _filename;
}
return _filename.substr(pos + 1);
}
bool setContent(const std::string &body)
{
std::ofstream ofs;
ofs.open(_filename, std::ios::binary);
if(ofs.is_open() == false)
{
std::cout << "setContent open failed\n";
return false;
}
ofs.write(&body[0], body.size());
if(ofs.good() == false)
{
std::cout << "setContent write failed\n";
ofs.close();
return false;
}
ofs.close();
return true;
}
bool getPosLen(std::string *body, size_t pos, size_t len)
{
std::ifstream ifs;
if(pos + len > fileSize())
{
std::cout << "getPosLen failed\n";
return false;
}
ifs.open(_filename, std::ios::binary);
if(ifs.is_open() == false)
{
std::cout << "getPosLen open failed\n";
return false;
}
body->resize(len - pos);
ifs.read(&(*body)[0], len);
if(ifs.good() == false)
{
std::cout << "getPosLen read failed\n";
ifs.close();
return false;
}
ifs.close();
return true;
}
bool getContent(std::string *body)
{
size_t n = fileSize();
return getPosLen(body, 0, n);
}
bool exists()
{
return fs::exists(_filename);
}
bool createDirectory()
{
if(exists())
return true;
return fs::create_directories(_filename);
}
bool getDirectory(std::vector<std::string> *arry)
{
for(const fs::directory_entry& entry : fs::directory_iterator{
_filename})
{
if(fs::is_directory(entry))
continue;
arry->push_back(fs::path(entry).relative_path().string());
}
return true;
}
bool compress(const std::string &packname)
{
std::string body;
getContent(&body);
std::string buffer = bundle::pack(bundle::LZIP, body);
std::ofstream ofs;
ofs.open(packname, std::ios::binary);
if(ofs.is_open() == false)
{
std::cout << "compress open failed\n";
return false;
}
ofs.write(&buffer[0], buffer.size());
if(ofs.good