进程IO--标准IO

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

1, 2007-7-30 15:16:42

2, 2007-7-30 15:16:43

该程序应该无限循环,直到按Ctrl-C中断程序。

再次启动程序写文件时可以追加到原文件之后,并且序号能够接续上次的序号,比如:

1, 2007-7-30 15:16:42

2, 2007-7-30 15:16:43

3, 2007-7-30 15:19:02

4, 2007-7-30 15:19:03

5, 2007-7-30 15:19:04

函数解析:

time();//获取系统当前时间,单位秒,从当前时间到1970.1.1的总秒数
time_t time(time_t *tloc);//*tloc=时间,return时间
time_t  t; 
time(&t);  //t = time(NULL);

localtime();//将时间秒数转换成年月时分秒格式
struct tm *localtime(const time_t *timep);
struct tm *tm;
tm = localtime();

sleep(1);//每隔一秒

fprintf();
int fprintf(FILE *stream, const char *format, ...);
功能:将字符串输出到文件中

sprintf();
int sprintf(char *str, const char *format, ...);
功能:将字符串存储在数组中
方法一:
#include<stdio.h>
#include<time.h>
#include<unitid.h>
int main(int argc,char const *argv[])
{
FILE *fp;//文件流
int a=0;//用于计算行数
char ch;
fp=fopen("test.txt","a+");//打开文件
    if(fp==NULL)//判断是否打开
        {
        printf("fopen error\n");
        return -1;
        }

    while((ch=fgetc(fp))!=EOF)//一次读取一个字符
        {
        if(ch=='\n')
        a++;
        }

    while(1)//循环
        {
        a++;//进入循环已经读了一个字符,所以先自加
        const long int m=time(NULL);
        struct tm *p=localtime(&m);
        fprintf(fp,"%d,%d-%d-%d %d:%d:%d\n",a,p->tm_year+1900,p->tm_mon+1,p->tm_mday,p->tm_         hour,p->tm_min,p->tm_sec);//向指定文件中输入
        ffush(NULL);
        printf("%d,%d-%d-%d %d:%d:%d\n",a,p->tm_year+1900,p->tm_mon+1,p->tm_mday,p->tm_hou          r,p->tm_min,p->tm_sec);
        sleep(1);
        }
    fclose(fp);
    return 0;

}
方法二:
#include<stdio.h>
#include<time.h>
#include<unitid.h>
int main(int argc,char const *argv[])
{
FILE *fp;//文件流
int a=0;//用于计算行数
char ch[32]="";
fp=fopen("test.txt","a+");//打开文件
    if(fp==NULL)//判断是否打开
        {
        printf("fopen error\n");
        return -1;
        }

    while(fgets(ch,32,fp)!=NULL)//一次读取一行
        {
        if(ch[strlen(ch)-1]=='\n')
        a++;
        }

    while(1)//循环
        {
        a++;//进入循环已经读了一行字符,所以先自加
        const long int m=time(NULL);//const long相当于time_t
        struct tm *p=localtime(&m);
        fprintf(fp,"%d,%d-%d-%d %d:%d:%d\n",a,p->tm_year+1900,p->tm_mon+1,p->tm_mday,p->tm_         hour,p->tm_min,p->tm_sec);//向指定文件中输入
        ffush(NULL);
        //printf("%d,%d-%d-%d %d:%d:%d\n",a,p->tm_year+1900,p->tm_mon+1,p->tm_mday,p->tm_hou          r,p->tm_min,p->tm_sec);
        sleep(1);
        }
    //fclose(fp);
    return 0;

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值