Chi*_*gno 4 c++ datetime date ctime localtime
我正在用C++编写一个简单的日志记录类用于学习目的.我的代码包含一个返回今天日期字符串的函数.但是,每当调用"localtime"时,我都会收到编译错误.
std::string get_date_string(time_t *time) {
struct tm *now = localtime(time);
std::string date = std::to_string(now->tm_mday) + std::to_string(now->tm_mon) + std::to_string(now->tm_year);
return date;
}
Run Code Online (Sandbox Code Playgroud)
我试过用#define _CRT_SECURE_NO_WARNINGS.它没有工作,出现了同样的错误.我还尝试_CRT_SECURE_NO_WARNINGS在项目属性中放入预处理器定义.这给出了一个未解决的外部错误.
有没有人对如何做有任何想法?
Gal*_*lik 19
问题是它std::localtime不是线程安全的,因为它使用静态缓冲区(在线程之间共享).双方POSIX并Windows有安全的替代品:则localtime_r和localtime_s.
这是我做的:
inline std::tm localtime_xp(std::time_t timer)
{
std::tm bt {};
#if defined(__unix__)
localtime_r(&timer, &bt);
#elif defined(_MSC_VER)
localtime_s(&bt, &timer);
#else
static std::mutex mtx;
std::lock_guard<std::mutex> lock(mtx);
bt = *std::localtime(&timer);
#endif
return bt;
}
// default = "YYYY-MM-DD HH:MM:SS"
inline std::string time_stamp(const std::string& fmt = "%F %T")
{
auto bt = localtime_xp(std::time(0));
char buf[64];
return {buf, std::strftime(buf, sizeof(buf), fmt.c_str(), &bt)};
}
Run Code Online (Sandbox Code Playgroud)
Nul*_*ull -3
尝试在任何其他头文件#define _CRT_SECURE_NO_WARNINGS之前#include,如以下代码
#define _CRT_SECURE_NO_WARNINGS
#include <ctime>
//your code
Run Code Online (Sandbox Code Playgroud)