linux操作系統編程——每隔一秒往文本文件寫入時間

程序要求:

(1)讀寫一個test.txt文件,每隔1秒往文件中寫入一行時間日期數據;

1、 2012-8-7 1:2:3

....

(2)下次啓動程序時能夠追加到原文件之後,並且序號能夠銜接上原先序號;


程序如下:

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

int main(int argc, const char *argv[])
{
    FILE *file;
    struct tm *t1;
    time_t t;
    char buf[100];
    int line = 1;
    int c;

    memset(buf, 0, sizeof(buf));

    if ((file = fopen("test.txt", "a+")) < 0)
    {
        perror("failed to open test.txt");

        exit(-1);
    }

    while ((c = getc(file)) != EOF)      //計算行數,用於下次打開時能夠銜接上之前的行數
        if (c == '\n')
            line++;

    while (1)
    {
        time(&t);
        t1 = localtime(&t);     //獲取當前世界
        
        sprintf(buf, "%d, %d-%d-%d %d:%d:%d\n", line++, t1->tm_year + 1900, t1->tm_mon + 1, t1->tm_mday, t1->tm_hour, t1->tm_min, t1->tm_sec);
        fwrite(buf, sizeof(char), strlen(buf), file);
        fflush(file);
        
        sleep(1);
    }

    return 0;
}



發佈了66 篇原創文章 · 獲贊 7 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章