标准I/O库之标准I/O的效率

程序清单5-1 用getc和putc将标准输入复制到标准输出

#include "apue.h"

int
main( void )
{
    int    c;
    
    while(( c = getc( stdin )) != EOF )
        if( putc( c, stdout ) == EOF )
            err_sys( "output error" );
    
    if( ferror( stdin ))
        err_sys( "input error" );
    
    exit( 0 );
}

程序清单5-2 用fgets和fputs将标准输入复制到标准输出

#include "apue.h"

int
main( void )
{
   char    buf[MAXLINE];
    
    while( fgets( buf, MAXLINE, stdin ) != NULL )
        if( fputs( buf, stdout ) == EOF )
            err_sys( "output error" );
    
    if( ferror( stdin ))
        err_sys( "input error" );
    
    exit( 0 );
}

系统调用与普通的函数调用相比通常需要花费更多的时间。

结合《文件I/O之I/O的效率》篇,我们了解到的基本事实是:标准I/O库与直接调用read和write函数相比并不慢很多。

对于大多数比较复杂的应用程序,最主要的用户CPU时间是由应用本身的各种处理消耗的,而不是由标准I/O例程消耗的。

本篇博文内容摘自《UNIX环境高级编程》(第二版),仅作个人学习记录所用。关于本书可参考:http://www.apuebook.com/

原文地址:https://www.cnblogs.com/nufangrensheng/p/3505900.html