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");}
修改的版本比第七章的原始版本快大约两倍。