fprintf 不会将 const char * 打印到文件
我有一个简单的日志功能,需要打印当前日期和时间。我在返回 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 *
之外,所有内容都被打印。 为什么?
I have a simple log function that needs to print the current date and time. I'm doing it inside a function that returns a char *
. When I try to set this char *
into fprintf()
, it doesn't print me the string into the file: why?
Here is the function that constructs the date-time:
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;
}
Here is the log:
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);
Every thing is printed except the date/time char *
.
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已返回一个指向立即终止的内存缓冲区的指针。任何使用从
CurrentDateTime()
返回的指针的函数都依赖于垃圾。你的编译器应该警告你这一点。忽略编译器警告,后果自负。
相反,可以通过 char *buffer = malloc(50 * sizeof char); 分配此内存,或者使用 C++ 的内存分配机制来分配内存,该内存的生存时间比函数“活动”和运行的时间更长。
You've returned a pointer to a memory buffer that dies immediately. Any function that uses the pointer returned from
CurrentDateTime()
is relying upon garbage.Your compiler should have warned you about this. Disregard your compiler warnings at your own peril.
Instead, either allocate this via
char *buffer = malloc(50 * sizeof char);
or use C++'s memory allocation mechanisms to allocate memory that can live longer than the time the function is 'live' and running.