作业:设计程序,获取当前系统时间,把时间转换为特定格式”yy年mm月dd日 星期x tt:mm:ss”,并每隔1s写入到本地磁盘中一个叫做log.txt的文本中,如果文本不存在则创建。
/********************************************************************
*
* file name: 文件IO作业.md
* author: [email protected]
* date: 2024年5月9日
* function: 每隔一秒向logt.xt文本写入当前系统时间
* note: none
*
* CopyRight (c) [email protected] All Right Reseverd
*
********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
/*****************************************************************************
* 函数名称: UpdateFtime
* 函数功能: 输出当前时间
* 函数参数: FILE* file
* 返回结果: NONE
* 注意事项: NONE
* 函数作者: [email protected]
* 创建日期: 2024年5月9日
* 修改历史: 2024年5月9日
* 函数版本: 1.0
*
*****************************************************************************/
void UpdateFtime(FILE* file)
{
//通过已知time()函数获取时间
time_t Gettime = time(NULL);
//将秒时间转换为年月日等
struct tm * fileTime = localtime( &Gettime );
//把时间转换为格式“yy年mm月dd日 星期x tt:mm:ss”
fprintf(file,"%d年%d月%d日 星期%d %d:%d:%d\n", fileTime->tm_year + 1900,
fileTime->tm_mon + 1,
fileTime->tm_mday,
fileTime->tm_wday,
fileTime->tm_hour,
fileTime->tm_min,
fileTime->tm_sec);
//进行刷新
fflush(file);
}
int main(int argc ,const char* arvg[])
{
int i = 0;
//判断传入的参数是否符合
if (2 != argc)
{
printf("Argument is invaild!\n");
exit(1);
}
//打开待写入文件(wb),如果文件不存在,wb+能够帮助创建
FILE *fp = fopen(argv[1],"wb+");
if (NULL == fp)
{
printf("Fopen %s is error!\n",argv[1]);
exit(1);
}
//循环写入
while(1){
UpdateFtime(file);
printf("program has run %d秒\n", i++);
//每隔一秒进行打印输出
sleep(1);
}
//关闭文件
fclose(file);
return 0;
}
标签:文件,IO,写入,fileTime,一秒,tm,file,include
From: https://www.cnblogs.com/luo-tt/p/18183345