#include <stdio.h>
#include <time.h>//time(),localtime()
#include <unistd.h>//sleep()
#include <string.h>
int main(int argc, const char *argv[])
{
int len = 0;
char buf[64];
FILE *fp;
time_t t;
struct tm *tp;
#if 1
if(argc < 2)
{
fprintf(stdout,"usage:%s <file name>\n",argv[0]);
return -1;
}
if((fp = fopen(argv[1],"a+")) == NULL)
{
perror("fopen");
return -1;
}
#else
if((fp = fopen("test.txt","a+")) == NULL)
{
perror("fopen");
return -1;
}
#endif
while(fgets(buf,64,fp) != NULL)
{
if(buf[strlen(buf)-1] == '\n')
len ++;
}
while(1)
{
time(&t);
tp = localtime(&t);
fprintf(fp,"%04d,%d-%02d-%02d %02d:%02d:%02d\n",++len,tp->tm_year+1900,tp->tm_mon+1,tp->tm_mday,
tp->tm_hour,tp->tm_min,tp->tm_sec);
fflush(fp);
sleep(1);
}
if(fclose(fp) == EOF)
{
perror("fclose");
return -1;
}
return 0;
}
运行结果