diff --git a/include/of_str.h b/include/of_str.h index 0a6698a..fba8eb0 100644 --- a/include/of_str.h +++ b/include/of_str.h @@ -15,6 +15,10 @@ public: static ofString replace(const ofString& str, const ofString& from, const ofString& to); static std::vector split(const ofString& input, const ofString& delimiter); static ofString trim(const ofString& input); + /// @brief 获取一个添加当前日期后缀的字符串(到秒,如 some.txt => some_20150115151221.txt)。 + /// @param name + /// @return + static ofString get_ofile_name(const ofString& name); }; }; // namespace ofen diff --git a/src/of_str.cpp b/src/of_str.cpp index 8a8f0ea..63e6fb5 100644 --- a/src/of_str.cpp +++ b/src/of_str.cpp @@ -1,4 +1,9 @@ #include "of_str.h" +#include +#include +#include +#include +#include namespace ofen { COfStr::COfStr() @@ -40,4 +45,27 @@ ofString COfStr::trim(const ofString& input) size_t end = input.find_last_not_of(ofT(" \t\n\r\f\v")); return input.substr(start, end - start + 1); } +ofString COfStr::get_ofile_name(const ofString& name) +{ + auto now = std::chrono::system_clock::now(); + std::time_t now_c = std::chrono::system_clock::to_time_t(now); + std::tm local_tm = *std::localtime(&now_c); + + std::ostringstream oss; + oss << std::put_time(&local_tm, "%Y%m%d%H%M%S"); + ofString timestamp; +#ifdef UNICODE_OFSTR + std::string temp = oss.str(); + timestamp.assign(temp.begin(), temp.end()); +#else + timestamp = oss.str(); +#endif + size_t dot_pos = name.find_last_of(ofT('.')); + if (dot_pos == ofString::npos) { + return name + ofT("_") + timestamp; + } + ofString base_name = name.substr(0, dot_pos); + ofString extension = name.substr(dot_pos); + return base_name + ofT("_") + timestamp + extension; +} } // namespace ofen