1、
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <utime.h>
/*
编写一个模拟时钟,在文件print.txt中每隔一秒进行打印一次。
累计打印次数,由另一个文件scanf.txt读入的数据确定。
提示:可以使用sleep(1) 进行延时1s ,头文件在<unistd.h>
*/
int main()
{
time_t t1;
struct tm *tdate;
char tim[50];
FILE *fp=NULL;
fp=fopen("pritf.txt","w");
int i=0;
FILE *pf=NULL;
pf=fopen("scanf.txt","w");
while(1)
{
sleep(1);
time(&t1);
tdate=localtime(&t1);//将时间戳转换位日历
size_t ret=strftime(tim,50,"%Y年%m月%d日 %H:%M:%S",tdate);
fprintf(fp,"%s",tim);
i++;
fprintf(pf,"%d",i);
}
fclose(fp);
fclose(pf);
return 0;
}
2、
/*
编写一个函数,返回当前时间的秒数,毫秒数,微秒数,纳秒数
*/
// #include <sys/times.h>
#include <stdio.h>
#include <time.h>
#include <utime.h>
#include <stdlib.h>
int main()
{
//1970.1.1 0时0分0秒至今
time_t t1;
time_t ret;
ret=time(&t1);
//time()函数返回值就是时间戳,实参是地址,地址里面的内容也是时间戳
printf("秒:%lld\n",ret);
// printf("%lld\n",t1);
struct timespec s1;
clock_gettime(CLOCK_REALTIME,&s1);
long long ms=s1.tv_sec*1000+s1.tv_nsec/1000000;
printf("毫秒:%lld\n",ms);
long long us=s1.tv_sec*1000*1000+s1.tv_nsec/1000;
printf("微秒:%lld\n",us);
long long as=s1.tv_sec*1000*1000*1000+s1.tv_nsec;
printf("纳秒:%lld\n",as);
return 0;
}
结果
秒:1660217658
毫秒:1660217658255
微秒:1660217658255384
纳秒:1660217658255384300
--------------------------------
Process exited after 0.1986 seconds with return value 0
请按任意键继续. . .