获取系统时间

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

/*************************************************
 *
 *   file name:GetCurTime.c
 *   author   :momolyl@126.com
 *   date     :2024/05/08
 *   brief    :获取当前系统时间,把时间转换为特定格式”yy年mm月dd日 星期x tt:mm:ss”,
 *             并每隔1s写入到本地磁盘中一个叫做log.txt的文本中,如果文本不存在则创建。
 *   note     :None
 *
 *   CopyRight (c) 2024    momolyl@126.com    All Right Reseverd
 *
 **************************************************/
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#include <unistd.h>
/*************************************************
 *
 *   func name     :main
 *   brief         :获取当前系统时间,把时间转换为特定格式”yy年mm月dd日 星期x tt:mm:ss”,
 *                  并每隔1s写入到本地磁盘中一个叫做log.txt的文本中,如果文本不存在则创建。
 *   func parameter:
 *                  @argc:由终端传入的参数的个数
 *                  @argv[0]:可执行文件
 *                  @argv[1]:要写入的文件指针
 *   return        :None
 *   note          :None
 *   func author   :momolyl@126.com
 *   date          :2024/05/08
 *   version       :V1.0
 **************************************************/
int main(int argc, const char *argv[])
{
    if (2 != argc) // 判断终端是否传入两个参数(可执行文件、log.txt的文件指针)
    {
        perror("argment is invaild!\n");
        exit(-1);
    }

    // 1.打开log.txt文件,如果没有则创建,并做错误处理
    FILE *log = fopen(argv[1], "ab");
    if (log == NULL)
    {
        printf("open %s is failed!\n", argv[1]);
    }

    // 2.获取当前系统时间
    const char *weekday[] = {"日", " 一", " 二", "三", "四", "五", "六"};
    while (1)
    {
        time_t CurrentTime;
        time(&CurrentTime);
        struct tm *time = localtime(&CurrentTime);
        fprintf(log, "%d年 %02d月 %02d日 星期%s %02d:%02d:%02d\n", time->tm_year + 1900, time->tm_mon + 1, time->tm_mday,
                weekday[time->tm_wday], time->tm_hour, time->tm_min, time->tm_sec);
        fflush(log);
        sleep(1);
    }

    return 0;
}

执行结果
image

posted @ 2024-05-08 21:14  铃是铃铛的铃  阅读(41)  评论(0)    收藏  举报