我有一个简单的日志功能,需要打印当前的日期和时间。我正在做一个返回char *
的函数。当我尝试将char *
设置为fprintf()
时,它不会将字符串打印到文件中:为什么?fprintf不打印const char *到文件
这里是构建日期时间函数:
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 *
。 为什么?
您应该_embrace_ C++,而不是用C++编译器编写C代码。无论如何,C++都有更好的方法(以C++方式来说更好),以格式化输出到字符串(和文件输出) - 例如参见'stringstream'。 – paxdiablo 2011-12-29 06:16:54
考虑使用'strftime()'来格式化来自'struct tm'的日期/时间值。此外,'const char * time'变量未被使用,不太可能有益。您很少需要在每条日志消息中记录编译日期和时间;您可以在打开日志时记录一次,以记录产品的哪个版本正在写入日志。 – 2011-12-29 08:05:46