思维导图
1、使用fgets统计一个文件的行号
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
int main(int argc, const char *argv[])
{
FILE *fp=NULL;
if((fp=fopen("a","r"))==NULL)
{
return -1;
}
int count=0;
char buf[10]="";
while(1)
{
char *res=fgets(buf,sizeof(buf),fp);
if(res==NULL)
{
break;
}
if(buf[strlen(buf)-1]=='\n')
{
count++;
}
}
printf("文件中有%d行\n",count);
fclose(fp);
return 0;
}
2、使用fgets、fputs3完成两个文件的拷贝
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
int main(int argc, const char *argv[])
{
if(argc>3)
{
return 0;
}
FILE *fp1=NULL;
FILE *fp2=NULL;
//定义两个文件指针,一个读一个写
if((fp1=fopen(argv[1],"r"))==NULL)
{
perror("");
return -1;
}
if((fp2=fopen(argv[2],"w"))==NULL)
{
perror("");
return -1;
}
char buf[10]="";
while(1)
{
char * res=fgets(buf,sizeof(buf),fp1);
if(res==NULL)
{
break;
}
fputs(buf,fp2);
}
fclose(fp1);
fclose(fp2);
return 0;
}
3、向文件中输出当前的系统时间.
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include <time.h>
#include<unistd.h>
int main(int argc, const char *argv[])
{
time_t old_time;
old_time=time(NULL);
struct tm *old_t=localtime(&old_time);
char buf[100];
int sec=old_t->tm_sec;
while(1)
{
time_t sys_time;
sys_time=time(NULL);
struct tm *t=localtime(&sys_time);
FILE *fp1=NULL;
//定义一个数行
if((fp1=fopen("time","r"))==NULL)
{
return -1;
}
//定义一个打印的指针
FILE *fp2=NULL;
if((fp2=fopen("./time","a"))==NULL)
{
return -1;
}
char temp;
int num=0;
while((temp=fgetc(fp1))!=EOF)
{
if(temp=='\n')
{
num++;
}
}
if(sec!=t->tm_sec)
{
sprintf(buf,"%02d、%04d-%02d-%02d %02d:%02d:%02d\n",num,t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
fputs(buf,fp2);
sec=t->tm_sec;
}
fclose(fp1);
fclose(fp2);
}
return 0;
}