思维导图
练习
1> 使用fgets统计一个文件的行号
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
if(argc != 2)
{
printf("file count error\n");
printf("usage:./a.out file");
return -1;
}
FILE *fp;
if((fp = fopen(argv[1],"r")) == NULL)
{
perror("open file");
return -1;
}
char buf[10];
int line=0;
while(fgets(buf,sizeof(buf),fp) != NULL)
{
if(buf[strlen(buf)-1] == '\n')
line++;
}
printf("line = %d\n",line);
fclose(fp);
return 0;
}
2> 使用fgets、fputs拷贝文件
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
if(argc != 3)
{
printf("file count error\n");
printf("usage:./a.out srcfile destfile\n");
return-1;
}
FILE *srcfp,*destfp;
if((srcfp = fopen(argv[1],"r")) == NULL)
{
perror("open srcfile");
return -1;
}
if((destfp = fopen(argv[2],"w")) == NULL)
{
perror("open destfile");
return -1;
}
char buf[10];
while(fgets(buf,sizeof(buf),srcfp) != NULL)
{
fputs(buf,destfp);
}
fclose(srcfp);
fclose(destfp);
return 0;
}