首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

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

2013-03-13 
C程序设计(第二版 新版)第八章 习题1. 用read、write、open和close 系统调用代替标准库中功能等价的函数,从

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

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");}

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

 

 

热点排行