文件IO笔试题

文件IO

笔试题

作业:设计程序,获取当前系统时间,把时间转换为特定格式”yy年mm月dd日 星期x tt:mm:ss”,并每隔1s写入到本地磁盘中一个叫做log.txt的文本中,如果文本不存在则创建。

代码:

/*****************************************************************************************************************
*	
*	file name	:	FileTime.c
*	author	 	:	cnzycwp@126.com
*	data  	 	:	2024/05/09
*	function	:	实现获取当前时间并每隔1秒写入本地磁盘中一个叫做log.txt的文本中
*	note	 	:	None
* 	
*  	CopyRight (c)	2024	cnzycwp@126.com 	All Right Reseverd
*
* ****************************************************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<time.h>

//用户自定义缓冲区的大小
//#define BUFFRSIZE 512

int main(int argc, char const *argv[])
{
    //1.由于写入时间的文件路径需要通过命令行传递,则需要分析命令行参数数量是否符合需求
    if (2 != argc)
    {
        printf("Argument is invaild!\n");
        exit(1);
    }
    
    //2.打开待写入文件(wb),若文本不存在则创建文本
    FILE *fp = fopen(argv[1],"w+b");
    if (NULL == fp)
    {
        printf("Fopen %s is error!\n",argv[1]);
        exit(1);
    }
    
    //3.获取当前系统时间,并把时间转换为特定格式“yy年mm月dd日 星期x tt:mm:ss”
    // time_t Tseconds = time(NULL);
    // struct tm *ft = localtime(&Tseconds);
    // int tm_year = (ft->tm_year) + 1900;
    // int tm_mon  = (ft->tm_mon) + 1;
    // int tm_mday = ft->tm_mday;
    // int tm_wday = ft->tm_wday;
    // int tm_hour = ft->tm_hour;
    // int tm_min  = ft->tm_min;
    // int tm_sec  = ft->tm_sec;

    //定义年月日,星期,时分秒变量
    int tm_year,tm_mon,tm_mday,tm_wday,tm_hour,tm_min,tm_sec;

    //3.每隔1s写入本地磁盘中一个叫做log.txt的文本中
    while (1)
    {
        //4.获取当前系统时间,并把时间转换为特定格式“yy年mm月dd日 星期x tt:mm:ss”
        time_t Tseconds = time(NULL);
        struct tm *ft = localtime(&Tseconds);
        tm_year = (ft->tm_year) + 1900;     //年从1900年开始
        tm_mon  = (ft->tm_mon) + 1;         //月份从0开始
        tm_mday = ft->tm_mday;
        tm_wday = ft->tm_wday;
        tm_hour = ft->tm_hour;
        tm_min  = ft->tm_min;
        tm_sec  = ft->tm_sec;
        fprintf(fp,"%d年%d月%d日,星期%d,%d:%d:%d",tm_year,tm_mon,tm_mday,tm_wday,tm_hour,tm_min,tm_sec);
        //fwrite(data_buffer,BUFFRSIZE,1,fp);
        fflush(fp);                         //刷新文件方便查看文件
        fprintf(fp,"\n");

        sleep(1);                           //休眠1秒
    }

    //5.完成写入动作,关闭文件
    fclose(fp);

    return 0;
    

}

结果验证:

image

posted @ 2024-05-09 21:19  陳文鹏  阅读(18)  评论(0编辑  收藏  举报