题目一 使用fgets统计给定文件的行号
#include <myhead.h>
int main(int argc, const char *argv[])
{
//判断传入的参数是否为2个
if (argc != 2)
{
printf("input file error!!!\n");
printf("usage:./a.out fileName\n");
return -1;
}
//表示传过来的有一个文件
//定义文件指针
FILE *fp = NULL;
if ((fp = fopen(argv[1], "r")) == NULL)
{
printf("fopen error\n");
return -1;
}
char buf[128];
int count = 0;
while (fgets(buf, sizeof(buf), fp) != NULL)
{
count++;
}
printf("该文件内容的行数为:%d\n", count);
// 关闭文件
fclose(fp);
return 0;
}
题目二 用fgets和fputs完成两个文件的拷贝
#include <myhead.h>
int main(int argc, const char *argv[])
{
//判断传入的是否为三个文件
if (argc != 3)
{
printf("input file error\n");
printf("usage:./a.out srcfile destfile\n");
return -1;
}
//以只读的形式打开源文件
FILE *sfp = NULL;
if ((sfp = fopen(argv[1], "r")) == NULL)
{
printf("open src file error\n");
return -1;
}
//以只写的形式打开目标文件
FILE *dfp = NULL;
if ((dfp = fopen(argv[2], "w")) == NULL)
{
printf("open destfile error\n");
return -1;
}
//开始copy逻辑
//定义搬运工
char buf[128];
while (fgets(buf, sizeof(sfp), sfp) != NULL)
{
fputs(buf, dfp); //将读取的一行数据写入
}
printf("拷贝成功\n");
fclose(sfp); //关闭俩文件
fclose(dfp);
return 0;
}