1、将课堂程序重新敲一遍
使用fgetc完成求一个文件的行号
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
if(argc!=2)
{
printf("input file error\n");
printf("usage:./a.out filename\n");
return -1;
}
FILE *fp;
if((fp=fopen(argv[1],"r"))==NULL)
{
perror("fopen error");
return -1;
}
char buf,h=0;
while((buf=fgetc(fp))!=EOF)
{
if(buf=='\n')
{
h++;
}
}
printf("行数=%d\n",h);
fclose(fp);
return 0;
}
使用fgetc、fputc完成两个文件的拷贝
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
if(argc!=3)
{
printf("input file error\n");
printf("usage:./a.out filename1 filename2\n");
}
FILE *fp;
if((fp=fopen(argv[1],"r"))==NULL)
{
perror("fopen error");
return -1;
}
FILE *fp1;
if((fp1=fopen(argv[2],"w"))==NULL)
{
perror("fopen error");
return -1;
}
char buf,h=0;
while(1)
{
buf=fgetc(fp);
if(buf==EOF)
{
break;
}
fputc(buf,fp1);
}
fclose(fp);
fclose(fp1);
return 0;
}
2、使用fgets完成求一个文件的行号
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
if(argc!=2)
{
printf("input file error\n");
printf("usage:./a.out filename\n");
return -1;
}
FILE *fp;
if((fp=fopen(argv[1],"r"))==NULL)
{
perror("fopen error");
return -1;
}
char buf[2],h=0;
while((fgets(buf,sizeof(buf),fp))!=NULL)
{
if(buf[0]=='\n')
{
h++;
}
}
printf("行数=%d\n",h);
fclose(fp);
return 0;
}
3、使用fgets、fputs完成两个文件的拷贝
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
if(argc!=3)
{
printf("input file error\n");
printf("usage:./a.out filename1 filename2\n");
}
FILE *fp;
if((fp=fopen(argv[1],"r"))==NULL)
{
perror("fopen error");
return -1;
}
FILE *fp1;
if((fp1=fopen(argv[2],"w"))==NULL)
{
perror("fopen error");
return -1;
}
char buf[10];
while(1)
{
if(fgets(buf,sizeof(buf),fp)==NULL)
{
break;
}
fputs(buf,fp1);
}
fclose(fp);
fclose(fp1);
return 0;
}
4、思维导图