开发者

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 a开发者_运维问答fter 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.

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:

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. 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. ctime() and its related functions can generate more useful strings for you.


What everyone is saying about __TIME__ is correct. Here's a link about the ctime library.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜