C/C++ 实现取得当前时间

C/C++ 实现取得当前时间

 

[cpp] 
  1. #include<stdio.h>
  2. #include<time.h>
  3. #include<errno.h>
  4. #include<string.h>
  5. #include<unistd.h>
  6. #define N 10
  7. int main(int argc,char *argv[])
  8. {
  9.     FILE *fp;
  10.     int line=0;
  11.   char buf[N];
  12.   if((fp=fopen(“test.txt”,”a”))==NULL)
  13.   {
  14.         fprintf(stderr,”fopen failed:%s\n”,strerror(errno));
  15.          return (-1);
  16.   }
  17.   while(fgets(buf,N,fp)!=NULL)
  18.   {
  19.       if(strlen(buf)<N-1||buf[N-2]==’\n’)
  20.       line++;
  21.   }
  22.   while(1)
  23.   {
  24.      time_t t;
  25.      time( &t);
  26.      struct tm *t1;
  27.      t1=localtime(&t);
  28.     sprintf(buf,”%d  %d/ %d/ %d %d:%d:%d\n”,++line ,t1->tm_year+1900,
  29.                                                  t1->tm_mon+1,
  30.                                                  t1->tm_mday,
  31.                                                  t1->tm_hour,
  32.                                                  t1->tm_min,
  33.                                                  t1->tm_sec),
  34.     printf(“%s”,buf);
  35.     fputs(buf,fp);
  36.     fflush(fp);
  37.     sleep(1);
  38.   }
  39.   fclose(fp);
  40.   return 0;
  41. }

 

 

示例效果:

 

标签