C程序设计(第二版 新版)第八章 习题

本文通过替换标准库函数为系统调用read、write、open和close,重新实现了cat程序,并对比了优化前后的执行效率。实验证明,新版本的运行速度几乎提升了一倍。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 用read、write、open和close 系统调用代替标准库中功能等价的函数,从写第七章cat程序,并通过实验比较两个版本的相对执行速度。

第七章的cat程序:

#include<stdio.h>

int main(int argc, char *argv[])
{
	FILE *fp;
	void filecopy(FILE *ifp, FILE *ofp);
	
	if(argc == 1)
	    filecopy(stdin, stdout);
	else
	   while(--argc > 0)
		if((fp = fopen(*++argv,"r")) == NULL)
		{
			printf("cat: cant't open %s\n",*argv);
			return 1;
		}
		else
		{
			filecopy(fp, stdout);
			fclose(fp);
		}
	return 0;
}

void filecopy(FILE *ifp, FILE *ofp)
{
	int c;
	
	while((c = getc(ifp)) != EOF)
		putc(c ,ofp);
}


改写后的cat.c程序:

#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>

int main(int argc, char *argv[])
{
	int f;
	void filecopy(int f1, int f2);

	if(argc == 1)
		filecopy(0,1);
	else
	{
		while(--argc > 0)
			if((f = open(*++argv,O_RDONLY,0)) == -1)
			{
				error("cat: can't open %s\n",*argv);
				return 1;
			}
			else
			{
				filecopy(f,1);
				close(f);
			}
		
	}
}

void filecopy(int f1, int f2)
{
	char buf[BUFSIZ];
	int n;

	while((n = read(f1,buf,BUFSIZ)) > 0)
		if(write(f2,buf,n) != n)
			error("cat: write error on file\n");
}

修改的版本比第七章的原始版本快大约两倍。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值