利用标准IO获取当前系统时间并输出到文本
文件IO
调用的接口函数
思路
1.调用time()和localtime()接口函数获取系统时间
2.将结构体返回的成员值存到变量里
3.利用sprintf()将存储的整数转换成字符串并放入缓冲区
4.将缓冲区中的内容写入文件
代码
/*************************************************************************************
*
* file name: 1.c
* author : lu.ciana.598393@gmail.com
* date : 2024/05/09
* function : 利用标准IO获取当前系统时间并输出到文本
* note : none
* CopyRight (c) 2024 lu.ciana.598393@gmail.com All Right Reserved
*
************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main()//(int argc, const char * argv[])
{
//if (2 != argc)
//{
//printf("Argument Is Invaild\n");
//exit(1);
//}
//2.打开文件并错误处理
FILE *file = fopen("./log.txt","w+b");
if (NULL == file)
{
perror("Fopen File Failed!");
exit(1);
}
char w_buf[52];
int sec,min,hour,day,week,mon,year;
while(1)
{
//利用循环获取系统时间并将它存入变量
time_t time_sum = time(NULL);
struct tm *CurTime = localtime(&time_sum);
sec = CurTime->tm_sec;
min = CurTime->tm_min;
hour = CurTime->tm_hour;
day = CurTime->tm_mday;
week = CurTime->tm_wday;
mon = CurTime-> tm_mon + 1;
year = CurTime-> tm_year +1900;
//将变量里的整数用spritf函数全部转换成字符串
sprintf(w_buf,"%d年%d月%d日 星期%d %d:%d:%d\n",year,mon,day,week,hour,min,sec);
//将缓冲区的内容写入文件中
fwrite(w_buf,strlen(w_buf),1,file);
fflush(file);
sleep(1);
}
//printf("sec=%d\n",sec);
//printf("min=%d\n",min);
//printf("hour=%d\n",hour);
//printf("day=%d\n",day);
//printf("week=%d\n",week);
//printf("mon=%d\n",mon);
//printf("year=%d\n",year);
fclose(file);
}