我遇到了一个非常奇怪的问题。我的时间根本没有改变,并且总是将相同的时间打印到日志文件中。这是一个覆盖上次的函数,并且应该返回新的:
char * update_time(char *date)
{
time_t timer;
timer = time(&timer);
struct tm* time_real;
time_real = localtime(&timer);
date = asctime(time_real);
strftime(date, 26, "%Y.%m.%d %H:%M:%S", time_real);
return date;
}
这是我如何调用该函数来获取新时间:
date = update_time(date);
在主函数中,我声明一个指向 char 的指针,如下所示:
char *date = NULL;
每次我需要获取新数据时都调用该函数。更有趣的是,当我逐行调试程序时,我看到调试器“看到” char *data 的新值,但在结果文件中看不到(打印)它。
这里是输出 txt 文件:
2015.04.16 20:09:49:09S Program starts
2015.04.16 20:09:49:09S Opening file: a.txt
2015.04.16 20:09:49:09S New data retrieved
2015.04.16 20:09:49:09S Closing file: a.txt
2015.04.16 20:09:49:09S End of program
感谢您提前提供帮助
编辑
用 Sleep(5000) 让我的程序小睡一下,@nos 和 @Weather Vane 是对的,这一切都与耗时有关(在我的问题中更有趣的是:D)。我们可以关闭此票证,感谢大家的帮助。
最佳答案
注意:asctime
在 MSVC 示例中被指出已被弃用,因为它使用内部静态数组。
考虑使用 asctime_s
来代替,它的输出采用缓冲区参数。
如果您使用asctime
,则必须在再次使用它之前复制其结果。除了立即使用之外,记住返回的指针是没有用的。
更新
我发现一个错误:
date = asctime(time_real); // overwrites the pointer you passed
trftimse(date, 26, "%Y.%m.%d %H:%M:%S", time_real); // passes the pointer provided by asctime
return date; // that's NOT the arg you passed
因此该函数使用指向 asctime
返回的静态内部字符串的指针,而不是您提供的指针。
你的问题表明了这一点
char *date = NULL;
date = update_time(date);
因此,您将 NULL
指针传递给 strftime
。它以前有效,因为对 asctime
的不相关调用用其内部静态指针替换了 NULL
指针。
但即使一切都正确,如果程序在很短的时间跨度内运行并完成,时间
的粒度意味着无法报告小的时间差异。
关于c - C语言中时间不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29683482/