1、fgets获取文件的行号。
代码展示
#include <myhead.h>
int main(int argc, const char *argv[])
{
if(argc != 2){
printf("外部参数错误!\n");
return -2;
}
FILE *fp = fopen("../1.txt","r");
if(fp == NULL){
perror("fp");
return -1;
}
int count = 0;
char s[9];
while( (fgets(s,sizeof(s),fp) != NULL )){
int len = strlen(s);
if(s[len-1] == '\n'){
count++;
}
printf("%s",s);
}
printf("文件行数为:%d\n",count);
fclose(fp);
return 0;
}
运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/6065fc21dd1c480ca491a7bec72e091a.png)
2、fgets和fputs拷贝文件
代码展示
#include <myhead.h>
int main(int argc, const char *argv[])
{
if(argc != 3){
printf("外部参数错误!\n");
return -1;
}
FILE *fp1 = fopen("./1.txt","r");
if(fp1 == NULL){
perror("fp1");
return -1;
}
FILE *fp2 = fopen("./2.txt","w");
if(fp2 == NULL){
perror("fp2");
return -1;
}
char s[100];
while( (fgets(s,sizeof(s),fp1)) != NULL){
fputs(s,fp2);
}
printf("复制成功!\n");
fclose(fp1);
fclose(fp2);
printf("复制后2.txt的内容:\n");
fp2 = fopen("./2.txt","r");
char r[100];
while( fgets(r,sizeof(r),fp2) != NULL){
fputs(r,stdout);
}
fclose(fp2);
return 0;
}
运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/2a82e5422c0c46939ad1324d482208c1.png)
思维导图
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/539ffa9d721b4e2e895b6ba9d6fc7a1f.png)