#ifndef FILELOGGER_H #define FILELOGGER_H #include #include #include #include // 跨平台路径分隔符:Windows用\,Linux/macOS用/ #ifdef _WIN32 #define PATH_SEPARATOR "\\" #else #define PATH_SEPARATOR "/" #endif /** * @brief 文件文本写入工具类 * 支持:跨平台写入、自动创建多级目录、覆盖/追加模式、char*兼容(需先转string) */ class FileLogger { public: // 写入模式枚举 enum class WriteMode { OVERWRITE, // 覆盖模式:清空现有内容 APPEND // 追加模式:在文件末尾添加(默认) }; public: /** * @brief 写入文本到文件(核心接口) * @param relativePath 相对路径(如 "log"、"data/logs") * @param fileName 文件名(如 "app.log"、"20240916.txt") * @param data 待写入的文本(std::string类型,char*需先转string) * @param mode 写入模式(默认APPEND) * @throw std::runtime_error 路径创建失败/文件打开失败时抛出异常 */ static void writeToFile(const std::string& relativePath, const std::string& fileName, const std::string& data, WriteMode mode = WriteMode::APPEND); private: /** * @brief 辅助函数:拼接路径与文件名(处理分隔符) */ static std::string joinPath(const std::string& path, const std::string& fileName); /** * @brief 辅助函数:自动创建多级目录 */ static void createDirectory(const std::string& relativePath); /** * @brief 辅助函数:获取当前时间戳(格式:YYYY-MM-DD HH:MM:SS) */ static std::string getCurrentTime(); }; #endif // FILELOGGER_H