1. 用fgetc实现,计算一个文件有几行,要求封装成函数,用命令行传参
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int file_line(FILE *fp)
{
int count=0;
char c;
while(1)
{
c=fgetc(fp);
if(c == '\n')
{
count++;
}
if(c==EOF)
{
break;
}
}
printf("%d\n",count);
return 0;
}
int main(int argc, const char *argv[])
{
//打开文件
FILE *fp=fopen(argv[1],"r");
if(NULL==fp)
{
perror("fgetc");
return -1;
}
//调用函数
file_line(fp);
//关闭文件
fclose(fp);
return 0;
}
ubuntu@ubuntu:1$ ls
a.out fgetc.c fgetc.txt
ubuntu@ubuntu:1$ gcc fgetc.c
ubuntu@ubuntu:1$ ./a.out fgetc.txt
6
ubuntu@ubuntu:1$ cat fgetc.txt
hello
nice
hahaha
happy
sad
good
2. 用fgets和fputs实现文件的拷贝
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
FILE *fp=fopen("./1.txt","r");
FILE *pp=fopen("./2.txt","w");
if(NULL==fp)
{
printf("%d\n",__LINE__);
perror("copy");
return -1;
}
if(NULL==pp)
{
printf("%d\n",__LINE__);
perror("copy");
return -1;
}
char str[32];
char *p=NULL;
while(1)
{
p=fgets(str,sizeof(str),fp);
if(NULL==p)
{
break;
}
printf("%s",str);
fputs(str,pp);
}
fclose(fp);
fclose(pp);
return 0;
}
ubuntu@ubuntu:2$ ls
1.txt 2.txt a.out copy.c
ubuntu@ubuntu:2$ gcc copy.c
ubuntu@ubuntu:2$ ./a.out
abcd ef f
sjfbhj d
shdbab
eqj
ubuntu@ubuntu:2$ cat 1.txt
abcd ef f
sjfbhj d
shdbab
eqj
ubuntu@ubuntu:2$ cat 2.txt
abcd ef f
sjfbhj d
shdbab
eqj
3. 用fgets实现计算一个文件有几行
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
FILE *fp=fopen("./wyl.txt","r");
if(NULL==fp)
{
perror("fgetsline");
return -1;
}
char str[32];
char *p=NULL;
int count=0;
while(1)
{
p=fgets(str,sizeof(str),fp);
if(NULL==p)
{
break;
}
count++;
}
printf("文件有%d行\n",count);
fclose(fp);
return 0;
}
ubuntu@ubuntu:3$ ls
a.out fgetsline.c wyl.txt
ubuntu@ubuntu:3$ gcc fgetsline.c
ubuntu@ubuntu:3$ ./a.out
文件有8行
ubuntu@ubuntu:3$ cat wyl.txt
abcde shhdc df
sh jkkhhis wjkji
jbas
jusa kjl
eej
2545
ssq