Chinaunix首页 | 论坛 | 博客
  • 博客访问: 588575
  • 博文数量: 165
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1554
  • 用 户 组: 普通用户
  • 注册时间: 2013-10-23 22:57
个人简介

我本仁慈,奈何苍天不许

文章分类

全部博文(165)

文章存档

2018年(1)

2016年(33)

2015年(5)

2014年(34)

2013年(92)

分类: LINUX

2013-10-24 22:28:12

 

编程读写一个文件test.txt,每隔一秒向文件中写入一行数据,类似这样:

1 2007-7-30  15:16:30

2 2007-7-30  15:16:31

改程序应该无限循环,直到按Ctrl-C中断程序,下次再启动程序些文件时可以追加到源文件之后,并且序号能够连续上次的序号。

下面用了两种差不多的方法:其中第二种方法在判断test.txt已经有多少行的算法上比较好,比第一种更节约CPU资源,后面有关于localtime函数中系统定义结构体里面的成员的值。

#include

#include

#include

#include

#include

int main()

{

       FILE *fp;

       struct tm *t;

       time_t now;

       char c;

       char str[100];

       int n = 1;

       if((fp = fopen("test.txt","a+")) == NULL)

       {

              printf("open file faiul\n");

              exit(1);

       }

/*下面这段代码使用来判断test.txt里面已经存在多少个行了*/

       while((c = getc(fp)) != EOF)

       {

              if(c == '\n')

              {

                     n++;

              }

       }

       while(1)

       {

              time(&now);

              t = localtime(&now);

              fprintf(fp,"%3d,  %d-%2d-%2d  %2d:%2d:%2d\n",n++,t->tm_year+1900,t->tm_mon+1,t->tm_mday+1,t->tm_hour,t->tm_min,t->tm_sec);

              //fwrite(str,sizeof(char),strlen(str),fp);

              fflush(fp);

              sleep(1);

       }

       fclose(fp);

       return 0;

}

#include

#include

#include

#include

#define error_sys(error) \

       do\

       {\

              perror("error");\

              exit(-1);\

       }while(0);

int

main (int argc, char *argv[])

{

       FILE *fp;

       time_t t;

       struct tm *p = NULL;

       char buff[64];

       int count = 0;

      

       if((fp = fopen(argv[1],"a+")) == NULL)

       {

              error_sys(fopen argv[1]);

       }

      

       while(fgets(buff, 64, fp))

       {

              if(buff[strlen(buff)-1] == '\n')

                     count++;

       }

      

       while(1)

       {

              time(&t);

              p = localtime(&t);

              fprintf(fp,"%d, %d-%d-%d %d:%d:%d\n",count++, p->tm_year+1900,p->tm_mon+1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);

              fflush(fp);

              sleep(1);

       }

      

       fclose(fp);      

       return 0;

}

阅读(3809) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~