/**************************************************
****************************************************/
#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();
}