Service_NSSM/CC_SDK/Include/Module/File/CCFile.h

103 lines
3.8 KiB
C
Raw Normal View History

2025-09-27 14:24:18 +08:00
#ifndef CCFiles_H
#define CCFiles_H
#include "CC.h"
#include <filesystem>
// 根据不同的操作系统进行特定的设置
#ifdef _WIN32
#elif __linux__
#endif
/**
* CCFileInfo用于存储文件信息
*/
struct CCFileInfo
{
CTL::String Name; // 文件名
size_t Size{}; // 文件大小
bool IsDirectory{}; // 是否为目录
time_t LastWriteTime;
2025-09-30 16:24:15 +08:00
CTL::String Path;
2025-09-27 14:24:18 +08:00
};
// 命名空间别名用于简化std::filesystem的使用
namespace CC_FS = std::filesystem;
// 类型别名,用于简化目录迭代器的使用
typedef CC_FS::directory_iterator CCDir;
// 类型别名,用于简化目录条目的使用
typedef CC_FS::directory_entry CCDirEntry;
/**
* CCFile类提供了对文件操作的支持
*/
class CCFile
{
public:
// 构造函数通过文件路径初始化CCFile对象
CCFile(const CTL::String& path);
// 构造函数通过目录条目初始化CCFile对象
CCFile(const CCDirEntry& entry);
//----------------------------------------------------------------------------
// 判断文件是否为目录
bool isDirectory() const;
// 删除文件或目录如果isAll为true则递归删除目录下的所有内容
bool Delete(bool isAll = false) const;
// 检查文件或目录是否存在
bool isExists() const;
// 判断文件是否为常规文件(非目录、符号链接等)
bool isRegular() const;
// 获取文件大小
size_t GetFileSize() const;
// 获取文件名
CTL::String GetName() const;
// 获取文件或目录的路径如果relative为true则返回相对路径
CTL::String GetPath(bool relative = true) const;
// 获取文件或目录的信息
CCFileInfo GetFileInfo() const;
//----------------------------------------------------------------------------
// 获取指定路径的目录列表迭代器
static CCDir DirectoryList(const CTL::String &path);
// 标准化路径,确保路径格式在不同操作系统下的一致性
static CTL::String NormalizePath(CTL::String path);
// 获取目录中的所有文件和子目录的信息
static CCVector<CCFileInfo> GetDirectoryContents(const CTL::String& directoryPath);
// 创建文件或目录如果Dir为true则尝试创建目录否则创建文件
static bool Create(const CTL::String& Path,bool Dir = false);
static bool Copy(const CTL::String& src,const CTL::String& dst);
static CTL::String GetRelativePath(const CTL::String& path,const CTL::String& basePath);
static CTL::String GetParentDir(const CTL::String& path);
static bool ReviseFileName(const CTL::String& OldPath,const CTL::String& NewPath);
private:
#ifdef _WIN32
CTL::CCWString Path; // 文件或目录的路径
#elif __linux__
CTL::String Path;
#endif
// 将时间点转换为指定格式的字符串
static time_t to_string(const CC_FS::file_time_type& time) {
2025-09-30 16:24:15 +08:00
#if __cplusplus >= 202002L // C++20及以上版本
// C++20提供了更直接的转换方法
auto sysTime = std::chrono::clock_cast<std::chrono::system_clock>(time);
return std::chrono::system_clock::to_time_t(sysTime);
#elif __cplusplus >= 201703L // C++17版本
// 对于C++17需要手动转换
auto systemTime = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
time - CC_FS::file_time_type::clock::now() + std::chrono::system_clock::now()
);
return std::chrono::system_clock::to_time_t(systemTime);
#else // 更早的C++版本
// 备用方案
auto duration = time.time_since_epoch();
auto secs = std::chrono::duration_cast<std::chrono::seconds>(duration);
return secs.count();
#endif
2025-09-27 14:24:18 +08:00
}
// 删除文件这是Delete函数的辅助函数
bool deleteFile() const;
};
#endif