输出时间和行号
方法一:统计行高
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
int main()
{
FILE *fp;
char Timer_Num[50];
time_t Compare=0;
int Num=1;
if((fp=fopen("./tmin.txt","a+"))==NULL)
{
perror("open file");
return -1;
}
while(fgets(Timer_Num,sizeof(struct tm)+3,fp)!=NULL)
{
Num++; //计算当前文件内行数
}
fclose(fp);
while(1)
{
time_t sys_time=time(NULL);
struct tm *fomattime=localtime(&sys_time);
if(Compare!=sys_time) //比较毫秒数是否改变
{
if((fp=fopen("./tmin.txt","a+"))==NULL)
{
perror("open file");
return -1;
}
sprintf(Timer_Num,"%4d-%02d-%2d %2d:%2d:%2d",
fomattime->tm_year+1900,
fomattime->tm_mon+1,
fomattime->tm_mday,
fomattime->tm_hour,
fomattime->tm_min,
fomattime->tm_sec);
fprintf(fp,"%d、%s\n",Num++,Timer_Num);
Compare=sys_time; //将更新过的时间赋给比较变量
fclose(fp);
}
}
return 0;
}
方法二:获取上一组时间的行号
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
int main()
{
FILE *fp;
char Timer_Num[50];
time_t Compare=0;
int Num=0,n=0;
while(1)
{
time_t sys_time=time(NULL);
struct tm *fomattime=localtime(&sys_time);
if(sys_time!=Compare) //判断时间是否发生更新
{
if((fp=fopen("./tmin.txt","a+"))==NULL)
{
perror("open file");
return -1;
}
n=0;
while((fgets(Timer_Num,sizeof(Timer_Num),fp))!=NULL); //将文件最后一行读到数组中
printf("%s",Timer_Num); //打印获得的上一次结束的时间串
while(Timer_Num[n]>='0'&&Timer_Num[n]<='9') //判断是否是数字
{
Num=Num*10+(Timer_Num[n]-'0'); //一位一位合成行号
n++; //数组移动到下一位
}
sprintf(Timer_Num,"%4d-%02d-%2d %2d:%2d:%2d", //合成时间
fomattime->tm_year+1900,
fomattime->tm_mon+1,
fomattime->tm_mday,
fomattime->tm_hour,
fomattime->tm_min,
fomattime->tm_sec);
Num++; //行号在上一行的基础上加一
fprintf(fp,"%d,%s\n",Num,Timer_Num); //向文件中写入行号和时间
Num=0; //清零行号,不干涉下次合成行号
Compare=sys_time; //将当前毫秒数赋给比较值等待下次时间更新
fclose(fp);
}
}
return 0;
}
文件复制
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
int main()
{
FILE *fp,*fp1;
char Buf[1024];
int n=0;
if((fp=fopen("./Text.txt","r"))==NULL)
{
perror("open file");
return -1;
}
if((fp1=fopen("./Text.txt_1","w"))==NULL)
{
perror("open file");
return -1;
}
while(1)
{
fread(&Buf[n],sizeof(char),1,fp);//一个一个字节读
n++; //统计文件的字节大小
if(feof(fp))
{
break;
}
else if(ferror(fp))
{
printf("error!");
break;
}
}
fwrite(Buf,n-1,1,fp1); //输出所有内容
fclose(fp);
fclose(fp1);
}