以可读可写可追加的方式显示系统时间,并且第二次执行记录下了第一次的行号,紧接着第一次的行号执行显示系统时间。
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define N 50
int main()
{
//char *wday[]=
//{"sun","mon","tue","wed", "thu","fri","sat"};// 显示系统星期几
FILE *fp;
int count=0;//定义行号
char buf[N];//
//char ch;
if((fp=fopen("test.txt","a+"))==NULL)
{
fprintf(stderr,"fopen failed : %s \n",strerror(errno) );
return EOF;
}
/*ch=fgetc(fp);
while(ch!=EOF)
{
if(fgetc(fp )!='\n')
count++;
ch=fgetc(fp);//一个一个字符的读 速度慢
}*/
//fseek(fp, 0, SEEK_SET);
while(fgets(buf,N,fp)!=NULL)//一行一行的读速度快,记住行号
{
count++;
}
printf("hang=%d\n", count);
while(1)// 强制显示系统时间
{
time_t timep;
struct tm *p;
time(&timep);
p=gmtime(&timep);
sprintf(buf,"%d %d-%d-%d %d:%d:%d\n",count++,(1900+p-> tm_year),(1+p-> tm_mon)\
,p-> tm_mday,p-> tm_hour,p-> tm_min,p-> tm_sec);
sleep(1);//每隔一秒显示系统时间
//count++;
printf("%s",buf);
fputs(buf,fp); //将buffer的值写入到fp中
fflush(fp);
}
fclose(fp);
return 0;
}