记录系统当前时间到一个文件中

本文介绍了一个使用C语言编写的程序,该程序能够记录系统的当前时间并将其写入到一个文本文件中。程序首先检查文件是否为空或是否存在,然后记录时间戳,包括日期和时间,并将这些信息追加到文件末尾。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

/**************************************************

****************************************************/

#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>

void record_systime(void)
{
    FILE *fp = NULL;
    time_t curtime = 0;
    struct tm *st = NULL;  /* struct tm defined in <time.h> */
    unsigned int count = 1;
    int ret = 0;
    char buf[81];
   
    fp = fopen("test.txt", "a+");
    if (fp == NULL)
    {
        printf("Open the test.txt file error!\n");
        exit(1);   
    }
   
    if (NULL == fgets(buf, 81, fp))      /* if the file is empty. */
    {
        count = 0;
        printf("the buf is:%s\n", buf);
        printf("The file is empty!\n");  
    }
    else
    {
        ret = fseek(fp, -30, SEEK_END);  /* the file is not empty, seek to start of the last line */
        if (-1 == ret)
        {
            printf("fseek error!\n");
            exit(1);   
        }
   
        if (NULL == fgets(buf, 81, fp))
        {
            printf("fgets error or get reach to the file's end!\n");   
        }
        printf("the buf is:%s\n", buf);
       
        while (buf[count++] != '\0')
            ;
        printf("the length of a line is: %d\n", --count);
       
        count = atoi(buf); 
    }
    count++;
   
    while (1)
    {
        time(&curtime);    /* get the current time */
        st = localtime(&curtime); /* change the current to local time */
       
        /* write the time to the file */
        fprintf(fp, "%10d, %.4d-%.2d-%.2d %.2d:%.2d:%.2d\n", count, st->tm_year, st->tm_mon,\
            st->tm_mday, st->tm_hour, st->tm_min, st->tm_sec);
           
        fflush(fp); /* flush I/O buffer to the disk file */ 
                    /* or the data will not write to file until the I/O buffer is full */
        fprintf(stdout, "%10d, %.4d-%.2d-%.2d %.2d:%.2d:%.2d\n", count, st->tm_year, st->tm_mon,\
            st->tm_mday, st->tm_hour, st->tm_min, st->tm_sec);
        count++;
        sleep(1);   
    }
    fclose(fp);
}

int main(void)
{
   record_systime();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值