现在的位置: 首页 > 综合 > 正文

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

2014年07月07日 ⁄ 综合 ⁄ 共 721字 ⁄ 字号 评论关闭
文章目录

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

1  c 语言

#include<stdio.h>
#include<time.h>
#include<errno.h>
#include<string.h>
#include<unistd.h>
#define N 10
int main(int argc,char *argv[])
{
	FILE *fp;
	int line=0;


  char buf[N];
  if((fp=fopen("test.txt","a"))==NULL)
  {
    	fprintf(stderr,"fopen failed:%s\n",strerror(errno));
	
		 return (-1);
  }   

  while(fgets(buf,N,fp)!=NULL)
  {	
	  if(strlen(buf)<N-1||buf[N-2]=='\n')
	  line++;
  }
  while(1)
  {
	 time_t t;
 	 time( &t);
	 struct tm *t1;
 	 t1=localtime(&t);
 	sprintf(buf,"%d  %d/ %d/ %d %d:%d:%d\n",++line ,t1->tm_year+1900,
		                              			 t1->tm_mon+1,
												 t1->tm_mday,
												 t1->tm_hour,
												 t1->tm_min,
												 t1->tm_sec),

	printf("%s",buf);
	fputs(buf,fp);
	fflush(fp);
	sleep(1);
  }
  
  fclose(fp);
  return 0;


}

2 C++ 语言

#include<iostream>
#include<ctime>
using namespace std;
int main()
{
time_t now_time;
now_time = time(NULL);
cout<<now_time;
return 0;
}

示例效果:

抱歉!评论已关闭.