编程实现循环向文件中写入数据(自用)

编程读写一个文件test.txt,每隔1秒向文件中写入一行时间信息

类似:

1, 2007-7-30 15:16:42

2, 2007-7-30 15:16:43

程序可以无限循环,直到ctrl^c结束循环

再次启动程序时可以追加到原文件之后,并且序号可以续接

比如

1, 2007-7-30 15:16:42

2, 2007-7-30 15:16:43

3, 2007-7-30 15:19:02

4, 2007-7-30 15:19:03

5, 2007-7-30 15:19:04

sleep(1);可以实现睡眠一秒

用time();函数可以获取系统当前时间,单位:秒,从1970-1-1到当前时间

time_t time(time_t *tloc); //*tloc = 时间, return 时间;

time_t t;

time(&t); //t = time(NULL);

localtime();//将时间秒数转换成年月日时分秒格式

struct tm *localtime(const time_t *timep);

struct tm *tm;

tm = localtime();将时间秒数转换成年月日时分秒格式

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

int main(int argc, char const *argv[])
{
    FILE *fp;
    //打开文件,不存在创建,存在追加,第一次读时流被定位到文件开头,写始终在末尾
    fp = fopen("test.txt", "a+");
    if (NULL == fp)
    {
        perror("");
        return -1;
    }
    char buf[32] = "";
    int count = 0;
    time_t now;
    struct tm *tms;

    //行数追加
    while (fgets(buf, 32, fp))
    {
        if (buf[strlen(buf) - 1] == '\n')
            count++;
    }

    while (1)
    {
        now = time(NULL);
        tms = localtime(&now);
        count++;
        //向buf中写入时间信息
        sprintf(buf, "%d,%d-%d-%d %d:%d:%d\n", count, tms->tm_year + 1900, tms->tm_mon + 1, tms->tm_mday, tms->tm_hour, tms->tm_min, tms->tm_sec);
        
        printf("%s\n", buf);//向终端输出
        fputs(buf, fp);//向文件输出
        fflush(NULL);//强制刷新缓存
        sleep(1);//睡眠一秒
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值