编程读写一个文件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;
}