程序要求:
(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;
}