22081-10-8 day1 IO作业

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值