fprintf不会将const char *打印到文件中

时间:2011-12-29 06:01:47

标签: char printf localtime

我有一个简单的日志功能,需要打印当前的日期和时间。我在一个返回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 *外,每件事都打印出来。 为什么呢?

1 个答案:

答案 0 :(得分:5)

char * UT::CurrentDateTime()
{
     char buffer [50];
     /* ... */
     return buffer;
}

您已经返回指向内存缓冲区的指针,该内存缓冲区立即死亡。使用从CurrentDateTime()返回的指针的任何函数都依赖于garbage

您的编译器应该已经警告过您。忽略你的编译器警告,这是你自己的危险。

相反,要么通过char *buffer = malloc(50 * sizeof char);分配,要么使用C ++的内存分配机制来分配比函数“活动”并运行的时间更长的内存。