eis/dsm/utility.cc

101 lines
2.9 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 <dsm/utility.h>
namespace UtilityTools {
TimePoint time_point2zero(TimePoint time_point) {
return second_zero2time_point(time_point2second_zero(time_point));
}
int time_point2second_zero(TimePoint time_point) {
int seconds = (time_point.time_since_epoch().count()) / (size_t)pow(10, 9);
return 86400 * (int)((seconds + 28800) / 86400) - 28800;
}
TimePoint second_zero2time_point(int seconds) {
auto st_s = std::chrono::seconds(seconds);
auto time_date =
std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds>(
st_s);
return time_date;
}
TimePoint millsecond_zero2time_point(int64_t millseconds) {
auto st_s = std::chrono::milliseconds(millseconds);
auto time_date = std::chrono::time_point<std::chrono::system_clock,
std::chrono::milliseconds>(st_s);
return time_date;
}
int diff_days(TimePoint stime, TimePoint etime) {
return std::chrono::duration_cast<days>(etime - stime).count();
}
TimePoint string2TimePoint(std::string time_str, const std::string &fmt) {
std::tm tm = {};
std::stringstream ss(time_str);
ss >> std::get_time(&tm, fmt.c_str());
return std::chrono::system_clock::from_time_t(std::mktime(&tm));
}
int save_json_file(std::string path_ruleid, std::string file_name_date,
nlohmann::json content, std::string root_dir) {
try {
// 将 JSON 对象写入文件
std::string file_path = root_dir + "/" + path_ruleid;
std::string file_name = file_path + "/" + file_name_date + ".json";
if (fs::exists(file_name)) {
return 1;
}
if (create_path(file_path)) {
std::ofstream ofs(file_name); // 创建文件输出流对象,打开文件 "data.json"
ofs << content.dump(4); // 将 JSON 内容以字符串形式带4空格缩进写入文件
ofs.close(); // 关闭文件
return 0;
}
return -1;
} catch (const std::exception &e) {
throw;
return -1;
}
}
bool jsonReader(std::string file_path, json &sjson) {
// 1. 创建文件流并打开文件
std::ifstream file(file_path);
if (!file.is_open()) {
return false;
}
// 2. 解析JSON数据
try {
file >> sjson; // 方式1: 直接使用流操作符解析文件
// 也可以使用显式解析: jsonData = json::parse(file);
} catch (const std::exception &e) {
file.close();
return false;
}
// 3. 关闭文件
file.close();
return true;
}
bool create_path(std::string path) {
try {
// 检查路径是否存在
if (!fs::exists(path)) {
// 递归创建所有不存在的目录
return fs::create_directories(path);
}
} catch (const fs::filesystem_error &e) {
// 捕获并输出文件系统操作中的异常
throw;
return false; // 返回非零值表示错误
}
}
bool is_file_exists(std::string file_path){
return fs::exists(file_path);
}
} // namespace UtilityTools