我有一個簡單的日誌功能,需要打印當前的日期和時間。我正在做一個返回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