add:添加获取一个文件名的当前时间后缀的新名字函数。

This commit is contained in:
taynpg 2025-01-14 12:31:56 +08:00
parent 3d369e81c2
commit 2be0e96317
2 changed files with 32 additions and 0 deletions

View File

@ -15,6 +15,10 @@ public:
static ofString replace(const ofString& str, const ofString& from, const ofString& to);
static std::vector<ofString> 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

View File

@ -1,4 +1,9 @@
#include "of_str.h"
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <string>
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