Chinaunix首页 | 论坛 | 博客
  • 博客访问: 237894
  • 博文数量: 35
  • 博客积分: 791
  • 博客等级: 军士长
  • 技术积分: 510
  • 用 户 组: 普通用户
  • 注册时间: 2012-09-05 16:56
文章分类
文章存档

2013年(7)

2012年(28)

我的朋友

分类: 嵌入式

2012-09-05 17:00:07

程序要求:

(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.     }


阅读(9833) | 评论(0) | 转发(3) |
0

上一篇:没有了

下一篇:linux操作系统编程——简单的pipe管道

给主人留下些什么吧!~~