利用标准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);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义