【发布时间】:2012-01-29 16:11:46
【问题描述】:
我有一个简单的日志功能,需要打印当前日期和时间。我在返回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 * 外,所有内容都会被打印。
为什么?
【问题讨论】:
-
你应该拥抱 C++,而不是仅仅用C++编译器编写C代码。 C++ 有更好的(在 C++ 方面更好)的方式来对字符串(和文件输出)进行格式化输出 - 例如,请参见
stringstream。 -
考虑使用
strftime()格式化来自struct tm的日期/时间值。此外,“const char *time”变量未使用,不太可能有益。您很少需要在每条日志消息中记录编译日期和时间;您可以在打开日志时执行一次,以记录正在写入日志的产品版本。