利用标准IO获取当前系统时间并输出到文本

文件IO

image

调用的接口函数

image
image

思路

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);
}
posted @   luxiaolim  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示