我有一个简单的日志功能,需要打印当前日期和时间。我在一个返回char *
. 当我尝试将其设置char *
为fprintf()
时,它不会将字符串打印到文件中:为什么?
这是构造日期时间的函数:
char * UT::CurrentDateTime()
{
char buffer [50];
time_t t = time(0); // get time now
struct tm * now = localtime( & t );
int n=sprintf(buffer, "%d:%d:%d %d:%d:%d:", (now->tm_year + 1900),
(now->tm_mon + 1), now->tm_mday, now->tm_hour, now->tm_min,
now->tm_sec);
return buffer;
}
这是日志:
const char *time =__TIME__; // compilation time
char *currentTime = UT::CurrentDateTime(); // it's a static method; also tried to set it to const
fprintf(fp, "%s %s %s %s %s %d %s\n", __TIME__, pType, __DATE__,
currentTime, pFileName, lineNo, pMsg.c_str());
fflush(fp);
除日期/时间外,所有内容均已打印char *
。为什么?