Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1683168
  • 博文数量: 1493
  • 博客积分: 38
  • 博客等级: 民兵
  • 技术积分: 5834
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-19 17:28
文章分类

全部博文(1493)

文章存档

2016年(11)

2015年(38)

2014年(137)

2013年(253)

2012年(1054)

2011年(1)

分类:

2012-09-06 08:55:20

程序要求:

(1)读写一个test.txt文件,每隔1秒往文件中写入一行时间日期数据;

1、 2012-8-7 1:2:3

....

(2)下次启动程序时能够追加到原文件之后,并且序号能够衔接上原先序号;


程序如下:


点击(此处)折叠或打开

  1. #include <stdio.h>
  2.     #include <stdlib.h>
  3.     #include <string.h>
  4.     #include <time.h>
  5.       
  6.     int main(int argc, const char *argv[])
  7.     {
  8.         FILE *file;
  9.         struct tm *t1;
  10.         time_t t;
  11.         char buf[100];
  12.         int line = 1;
  13.         int c;
  14.       
  15.         memset(buf, 0, sizeof(buf));
  16.       
  17.         if ((file = fopen("test.txt", "a+")) < 0)
  18.         {
  19.             perror("failed to open test.txt");
  20.       
  21.             exit(-1);
  22.         }
  23.       
  24.         while ((c = getc(file)) != EOF) //计算行数,用于下次打开时能够衔接上之前的行数
  25.             if (c == '\n')
  26.                 line++;
  27.       
  28.         while (1)
  29.         {
  30.             time(&t);
  31.             t1 = localtime(&t); //获取当前世界
  32.               
  33.             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);
  34.             fwrite(buf, sizeof(char), strlen(buf), file);
  35.             fflush(file);
  36.               
  37.             sleep(1);
  38.         }
  39.       
  40.         return 0;
  41.     }


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