简体   繁体   English

简单的c程序不会产生所需的输出

[英]simple c program does not produce required output

I am using the following program to print the current time 我使用以下程序打印当前时间

int main() 
{
  printf("%s",__TIME__);
  return 0;
}

It works only for the first time. 它只适用于第一次。 If I run it after sometime it again gives the same old time. 如果我在一段时间后运行它再次给出相同的旧时间。

Why do I need to do to refresh the time ? 为什么我需要刷新时间呢?

__TIME__ is a standard predefined macro that expands to a string constant that describes the time at which the preprocessor is being run . __TIME__是一个标准的预定义宏 ,它扩展为一个字符串常量,用于描述预处理器的运行时间

It is replaced by the preprocessor just before the compilation. 它在编译之前被预处理器替换。 So it does not change with different runs. 所以不会随着不同的运行而改变。 But if you recompile your program you'll see the change. 但是如果你重新编译你的程序,你会看到变化。

To get the current time of the day you can use the time , localtime and asctime functions as: 要获取当天的当前时间,您可以使用timelocaltimeasctime函数:

time_t rawtime;
struct tm * timeinfo;

time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );

__TIME__ is a macro being set by your compiler. __TIME__是由编译器设置的宏。 Since it's fixed at compile time, running your program later won't change the output. 由于它是在编译时修复的,因此稍后运行程序不会更改输出。 You can call gettimeofday() or time() or even some other functions to get the time/date at runtime. 您可以调用gettimeofday()time()甚至其他函数来获取运行时的时间/日期。 ctime() and its related functions can generate more useful strings for you. ctime()及其相关函数可以为您生成更多有用的字符串。

What everyone is saying about __TIME__ is correct. 大家对__TIME__是正确的。 Here's a link about the ctime library. 这是关于ctime库的链接。

http://www.cplusplus.com/reference/clibrary/ctime/ctime/ http://www.cplusplus.com/reference/clibrary/ctime/ctime/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM