Files
dl_old/dl/io/dl_file.cpp
T
2023-12-28 11:25:26 +08:00

594 lines
12 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "io/dl_file.h"
#include <filesystem>
#include <regex>
#if DL_PLATFORM == DL_PLATFORM_WIN32
#include <Shlobj_core.h>
#endif
#include "io/dl_log.h"
#include "math/dl_algorithm.h"
#include "memory/dl_code_cvt.h"
#include "memory/dl_stream_input.h"
#include "memory/dl_stream_output.h"
#include "base/dl_string.h"
namespace dl::File
{
#if (DL_PLATFORM == DL_PLATFORM_ANDROID)
std::string_view CastU8StringView(std::string_view str)
{
return { str.data(), str.size() };
}
std::string ToString(std::string_view str)
{
return { (char*)str.data(), str.size() };
}
#else
std::u8string_view CastU8StringView(std::string_view str)
{
return { (char8_t*)str.data(), str.size() };
}
std::string ToString(std::u8string_view str)
{
return { (char*)str.data(), str.size() };
}
#endif
std::string_view CastStringView(std::u8string_view str)
{
return { (char*)str.data(), str.size() };
}
Buffer File::GetBuffer(std::ifstream& ifs)
{
Buffer ret;
ifs.seekg(0, std::ios::end);
ret.resize(ifs.tellg());
ifs.seekg(0, std::ios::beg);
ifs.read((char*)ret.data(), ret.size());
ifs.seekg(0, std::ios::beg);
return ret;
}
Buffer File::GetBuffer(std::string_view path_name)
{
std::ifstream ifs = Get(path_name, true);
if (!ifs.is_open())
{
log_err("文件打开失败: {}", path_name );
return {};
}
return GetBuffer(ifs);
}
//
//
//bool File::HashBlake2b(string_view path_name, Crypto::Blake2b& blake2b)
//{
// Buffer buf = GetBuffer(path_name);
// if (buf.Empty())
// return false;
//
// blake2b = Crypto::HashBlake2b(buf);
// buf.Delete();
//
// return true;
//}
//
//
//bool File::HashBlake2bCheck(string_view path_name, const Crypto::Blake2b& digest)
//{
// Buffer buf = GetBuffer(path_name);
// if (buf.Empty())
// return false;
//
// bool ret = Crypto::HashBlake2bCheck(buf, digest);
// buf.Delete();
//
// return ret;
//}
//
//
//uint32_t File::GetCrc32(string_view path_name)
//{
// Buffer buf = GetBuffer(path_name);
// if (buf.Empty())
// return 0;
//
// uint32_t ret = Crypto::HashCrc32(buf);
// buf.Delete();
// return ret;
//}
void File::GetPathFileAll(std::string_view path, std::vector<std::string>& ret,
std::string_view regex, bool recursion)
{
using directory_iterator = std::filesystem::directory_iterator;
std::list<directory_iterator> vec_path;
try
{
directory_iterator path_iter{ CastU8StringView(path) };
vec_path.push_back(path_iter);
}
catch (std::filesystem::filesystem_error& e)
{
log_err0(e);
return;
}
bool no_reg = true;
std::regex reg;
if (!regex.empty())
{
reg = std::string{ regex };
no_reg = false;
}
operate_front(vec_path, [&](const directory_iterator& iter_path)
{
for (auto& fe : iter_path)
{
if (fe.status().type() == std::filesystem::file_type::directory)
{
if(recursion)
vec_path.push_back(directory_iterator{ fe });
}
else
{
std::string path_name = fe.path().string();
//String::CvtPathSeparator(path_name);
if (no_reg || std::regex_search(path_name, reg))
ret.push_back(path_name);
}
}
});
}
void File::GetPathContent(std::string_view path, std::vector<std::string>& ret,
std::string_view regex, bool folder, bool file)
{
using directory_iterator = std::filesystem::directory_iterator;
directory_iterator path_iter;
try
{
path_iter = directory_iterator{ CastU8StringView(path) };
}
catch (std::filesystem::filesystem_error& e)
{
log_err0(e);
return;
}
bool no_reg = true;
std::regex reg;
if (!regex.empty())
{
reg = std::string{ regex };
no_reg = false;
}
for (auto& fe : path_iter)
{
if (fe.status().type() == std::filesystem::file_type::directory)
{
if (folder)
{
std::string path = fe.path().string();
ret.push_back(path);
}
}
else
{
if (file)
{
std::string path_name = fe.path().string();
if (no_reg || std::regex_search(path_name, reg))
ret.push_back(path_name);
}
}
}
}
FILE* File::GetFile(std::string_view path_name, bool is_binary /*= true*/)
{
//fp = nullptr;
//fopen_s(&fp, CodeCvt::cvt_u8_mb(path_name).c_str(), is_binary ? "rb" : "r");
//if (fp == nullptr)
// return 0;
//return 1;
FILE* ret = fopen(std::string{ path_name }.c_str(), is_binary ? "rb" : "r");
return ret;
}
// clang 暂不支持string_view传参
#if (DL_PLATFORM == DL_PLATFORM_WIN32)
#define DL_FILE_MAKE_STRING(str) str
#else
#define DL_FILE_MAKE_STRING(str) std::string{ str }
#endif
std::ifstream File::Get(std::string_view path_name, bool is_binary /*= true*/)
{
//CodeCvt::cvt_u8_mb(path_name)
//ifs.open(, is_binary ? (ifstream::binary | ifstream::in) : ifstream::in);
std::ifstream ret;
ret.open(DL_FILE_MAKE_STRING(path_name), is_binary ? (std::ifstream::binary | std::ifstream::in) : std::ifstream::in);
return ret;
}
bool File::ConvertMb2U8(std::string_view path_name, std::string_view out)
{
std::ifstream ifs = Get(path_name, false);
if (!ifs.is_open())
{
log_err("转换文件编码,文件加载失败:{}", path_name);
return false;
}
std::ofstream ofs;
ofs.open(DL_FILE_MAKE_STRING(out));
if (!ofs.is_open())
{
log_err("转换文件编码,文件创建失败:{}", out );
return false;
}
std::istreambuf_iterator<char> beg(ifs), end;
std::string str(beg, end);
ifs.close();
std::string str_u8 = CodeCvt::MultiByteToUtf8(str);
ofs << str_u8;
return true;
}
time_t File::GetLastWriteTime(std::string_view path_name)
{
using namespace std::filesystem;
using namespace std::chrono;
file_time_type t = last_write_time(path_name);
file_clock::time_point tp = file_time_type::clock::time_point(t);
nanoseconds dt = tp.time_since_epoch();
return (time_t)duration_cast<seconds>(dt).count();
// struct _stat64 fileInfo;
// std::string p = CodeCvt::Utf8ToMultiByte(path_name);
// if (_stat64(p.c_str(), &fileInfo) != 0)
// {
// log_err("获取文件信息失败: {}", path_name);
// }
// return fileInfo.st_mtime;
// return std::asctime(std::localtime(&cftime));
}
bool File::CheckPathFileModified(std::string_view path_name, std::string_view cache, bool update)
{
log_info("尝试对文件夹进行改动检查:{},cache:{}", path_name, cache);
constexpr uint32_t VERSION = 0;
struct SL
{
uint32_t _crc32;//32
char _pathName[520];//992
};
if (!IsExist(cache))
{//cache文件不存在
//按遍历加入即可
std::list<SL> list_sl;
std::vector<std::string> mul_file;
GetPathFileAll(path_name, mul_file);
//遍历文件夹所有文件,记录{path_name, write_time}
for (auto& iter : mul_file)
{
//log_info("开始读文件:{}", iter);
//
uint32_t crc32 = GetCrc32(iter);
SL sl;
sl._crc32 = crc32;
strcpy(sl._pathName, iter.c_str());
list_sl.emplace_back(sl);
}
//写入cache文件
StreamOutput s;
s.Write(&VERSION);
s.Write(&list_sl);
//
s.Save(cache);
}
else
{//cache文件存在
StreamInput s;
if (!s.LoadFromFile(cache))
{
log_err("输入流从cache加载失败:{}", cache);
return true;
}
//
uint32_t version;
s.Read(&version);
if (version != VERSION)
{
log_err0("VERSION值不匹配!");
return true;
}
std::list<SL> list_sl;
s.Read(&list_sl);
//读取到cache文件数据后,再与现有文件比对
bool not_match = false;
std::vector<std::string> mul_file;
GetPathFileAll(path_name, mul_file);
//数量不一致
if (list_sl.size() != mul_file.size())
{
not_match = true;
}
else
{
auto iter = list_sl.begin();
//遍历文件夹所有文件
for (auto& iter_file : mul_file)
{
//已经数据不够,说明新增加了文件
if (iter == list_sl.end())
{
not_match = true;
break;
}
//比较操作
uint32_t crc32 = GetCrc32(iter_file);
if (crc32 != iter->_crc32
|| iter_file != iter->_pathName)
{
log_msg("此文件发生了修改(或新增):{},crc32:{} -> {}",
iter_file, iter->_crc32, crc32);
not_match = true;
break;
}
++iter;
}
}
if (not_match && update)
{
//删除
Delete(cache);
//再重建
if (CheckPathFileModified(path_name, cache, false) == false)
log_err0("此处应该返回真。");
}
return not_match;
}
return true;
}
void File::DeleteContent(std::string_view path_name)
{
std::filesystem::path p{ CastU8StringView(path_name) };
if (!exists(p))
return;
for (auto& de : std::filesystem::directory_iterator(p))
{
std::filesystem::remove_all(de.path());
}
}
bool File::Copy(std::string_view source, std::string_view target)
{
std::filesystem::path p0{ CastU8StringView(source) };
std::filesystem::path p1{ CastU8StringView(target) };
std::error_code e;
copy(p0, p1, e);
if (e)
{
log_err0(to_string(e));
return false;
}
return true;
}
std::string File::GetExtension(std::string_view path_name, bool has_dot /*= false*/)
{
std::filesystem::path p{ CastU8StringView(path_name) };
std::string ret = ToString(p.extension().u8string());
if (!has_dot && !ret.empty())
return std::string{ ret.begin() + 1, ret.end() };
return ret;
}
std::string File::GetFilename(std::string_view path_name)
{
std::filesystem::path p{ CastU8StringView(path_name) };
return ToString(p.filename().u8string());
}
std::string File::GetStem(std::string_view path_name)
{
std::filesystem::path p{ CastU8StringView(path_name) };
return ToString(p.stem().u8string());
}
bool File::CreateFolder(std::string_view path)
{
if (path.empty())
return false;
std::filesystem::path p{ CastU8StringView(path) };
return create_directories(p);
}
std::string File::PathCurrent()
{
std::filesystem::path p = std::filesystem::current_path();
std::string ret = ToString(p.u8string());
ret += '/';
String::CvtPathSeparator(ret);
return ret;
}
std::string File::PathTemp()
{
std::filesystem::path p = std::filesystem::temp_directory_path();
std::string ret = ToString(p.u8string());
String::CvtPathSeparator(ret);
return ret;
}
#if DL_PLATFORM == DL_PLATFORM_WIN32
struct FileImp
{
std::string _pathAppDataLocal;
std::string _pathAppDataLocalLow;
std::string _pathAppDataRoaming;
std::string _pathProgramData;
void Build()
{
{
wchar_t str[MAX_PATH] = {};
SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, str);
_pathAppDataLocal = CodeCvt::WideCharToUtf8(str);
String::CvtPathSeparator(_pathAppDataLocal);
_pathAppDataLocalLow = _pathAppDataLocal + "Low/";
_pathAppDataLocal += "/";
}
{
wchar_t str[MAX_PATH] = {};
SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, str);
_pathAppDataRoaming = CodeCvt::WideCharToUtf8(str);
String::CvtPathSeparator(_pathAppDataRoaming);
_pathAppDataRoaming += "/";
}
{
wchar_t str[MAX_PATH] = {};
SHGetFolderPathW(NULL, CSIDL_COMMON_APPDATA, NULL, 0, str);
_pathProgramData = CodeCvt::WideCharToUtf8(str);
String::CvtPathSeparator(_pathProgramData);
_pathProgramData += "/";
}
}
};
#elif DL_PLATFORM == DL_PLATFORM_ANDROID
struct FileImp
{
std::string _pathFilesDir;
std::string _pathExternalFilesDir;
std::string _pathExternalStorageDirectory;
void Build()
{
// TODO
_pathFilesDir = "/data/data/com.lveyou.dltest/files/";
_pathExternalFilesDir = "/storage/emulated/0/Android/data/com.lveyou.dltest/files/";
_pathExternalStorageDirectory = "/storage/emulated/0/";
_pathExternalFilesDir = _pathFilesDir;
_pathExternalStorageDirectory = _pathFilesDir;
}
};
#endif
FileImp g_fileImp;
void InitFileSystem()
{
g_fileImp.Build();
}
std::string File::PathStorage()
{
#if DL_PLATFORM == DL_PLATFORM_WIN32
return g_fileImp._pathAppDataLocal + "dltest/";
#elif DL_PLATFORM == DL_PLATFORM_ANDROID
return g_fileImp._pathExternalFilesDir;
#endif
}
std::string File::PathPrivate()
{
#if DL_PLATFORM == DL_PLATFORM_WIN32
return g_fileImp._pathAppDataLocal + "dltest/";
#elif DL_PLATFORM == DL_PLATFORM_ANDROID
return g_fileImp._pathFilesDir;
#endif
}
std::string File::PathPublic()
{
#if DL_PLATFORM == DL_PLATFORM_WIN32
return g_fileImp._pathProgramData + "dltest/";
#elif DL_PLATFORM == DL_PLATFORM_ANDROID
return g_fileImp._pathExternalStorageDirectory;
#endif
}
bool File::IsExist(std::string_view path_name)
{
std::filesystem::path p{ CastU8StringView(path_name) };
return exists(p);
}
bool File::Delete(std::string_view path_name, bool all /*= false*/)
{
std::filesystem::path p{ CastU8StringView(path_name) };
return all ? remove_all(p) : remove(p);
}
bool File::SaveBuffer(BufferView buf, std::string_view path_name)
{
std::ofstream ofs(CodeCvt::Utf8ToMultiByte(path_name), std::ios::binary);
if (!ofs.is_open())
return false;
ofs.write((char*)buf.data(), buf.size());
return true;
}
uint32_t File::GetCrc32(std::string_view path_name)
{
return 0;
}
}