思维导图:
小练习:
使用fgets完成求一个文件的行号
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
FILE *fp; //定义一个文件指针
if ((fp=fopen("./test.txt","w"))==NULL)
{
perror("fopen error");
return -1;
}
fputs("Good Good Study\n",fp);
fputs("Day Day Up\n",fp);
fclose(fp);
if ((fp=fopen("./test.txt","r"))==NULL)
{
perror("fopen error");
return -1;
}
int line=0;
char buf[10];
while (fgets(buf,sizeof(buf),fp)!=NULL)
{
printf("%s",buf);
for(int i=0;i<strlen(buf);i++){
if(buf[i]=='\n'){
line++;
}
}
}
fclose(fp); //关闭fp指针打开的文件
printf("文件有%d行\n",line);
return 0;
}
使用fgets、fputs完成两个文件的拷贝
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(int argc, char const *argv[])
{
if(argc!=3){
printf("input file error\n");
printf("usage: ./cope srcfile destfile\n");
return -1;
}
FILE *srcfp,*destfp; //定义一个文件指针
if ((srcfp=fopen(argv[1],"r"))==NULL)
{
perror("srcfile open error");
return -1;
}
if ((destfp=fopen(argv[2],"w"))==NULL)
{
perror("destfile open error");
return -1;
}
char buf[10];
while ((fgets(buf,sizeof(buf),srcfp))!=NULL)
{
fputs(buf,destfp);
}
fclose(srcfp); //关闭fp指针打开的文件
fclose(destfp);
printf("拷贝成功\n");
return 0;
}