-
用fgetc实现,计算一个文件有几行,要求封装成函数,用命令行传参
-
#include <head.h> int getc_line(FILE *fp, int argc, char const *p) { char c; int line = 0; if (argc != 2)//命令行个数判断 { printf("格式错误\n"); return -1; } if ((fp = fopen(p, "r")) == NULL)//只读方式打开 PRINT_ERR("open file error"); while ((c = fgetc(fp)) != EOF)//循环判断条件,文件是否结束 { if (c == '\n') line++; } printf("line=%d\n", line + 1); } int main(int argc, char const *argv[]) { FILE *fp; char const *p = argv[1];//将命令行的参数赋值给p getc_line(fp, argc, p);//调用函数 fclose(fp); return 0; }
-
用fgets和fputs实现文件的拷贝。
-
#include <head.h> int main(int argc, char const *argv[]) { FILE *fp_a,*fp_b; if((fp_a=fopen("./01.txt","r"))==NULL)//只读方式打开源文件 PRINT_ERR("open file error"); if((fp_b=fopen("./02.txt","w"))==NULL)//只写方式打开目标文件 PRINT_ERR("open file error"); char str[20]; while((fgets(str,sizeof(str),fp_a))!=NULL)//循环条件,fgets返回值错误或者结束为NULL fputs(str,fp_b);//循环输出 fclose(fp_a); fclose(fp_b); return 0; }
-
用fgets实现计算一个文件有几行。
#include <head.h>
int main(int argc, char const *argv[])
{
FILE *fp;
char str[10];
int line=0;
if(argc!=2)//命令行参数个数判断
PRINT_ERR("格式错误");
if((fp=fopen(argv[1],"r"))==NULL)//只读打开源文件
PRINT_ERR("open file error");
while((fgets(str,sizeof(str),fp))!=NULL)//循环判断条件
//fgets失败或者结束的返回值为NULL
{
if(strlen(str)<9)//小于9就代表必定有一个换行符
{
line++;
continue;
}
if(str[strlen(str)-1]=='\n')//不小于9的话就代表字符串满或者最后一位是换行符
{
line++;
continue;
}
}
printf("line=%d\n",line);
fclose(fp);
return 0;
}