UNIX环境高级编程程序1-2将标准输入复制到标准输出

 
// mycat/mycat.c
__
#include "apue.h"

#define BUFFSIZE 4096

int main()
{
    int  n;
    char buf[BUFFSIZE];

    // By convention, all shells open three descriptors whenever a new program is run:
    // standard input, standard output, and standard error.
    // STDIN_FILENO specify the file descriptor for standard input
    // Unbuffered I/O is provided by the functions open, read, write, lseek, and close.
    // These functions all work with file descriptors.
    // The read function returns the number of bytes that are read, and this value is used
    // as the number of bytes to write. When the end of the input file is encountered, read
    // returns 0 and the program stops. If a read error occurs, read returns -1.
    while ((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0)
    {
        if (write(STDOUT_FILENO, buf, n) != n)
        {
            err_sys("write error");
        }
    }

    // usually n is bigger than 0, if input ctrl + d
    // then n is equal to 0
    if (n < 0)
    {
        err_sys("read error");
    }

    return 0;
}
// The standard I/O functions provide a buffered interface to the unbuffered I/O
// functions. Using standard I/O relieves us from having to choose optimal buffer sizes,
// such as the BUFFSIZE constant in Figure 1.4. The standard I/O functions also simplify
// dealing with lines of input (a common occurrence in UNIX applications). The fgets
// function, for example, reads an entire line. The read function, in contrast, reads a
// specified number of bytes. As we shall see in Section 5.4, the standard I/O library
// provides functions that let us control the style of buffering used by the library.
// The most common standard I/O function is printf. In programs that call
// printf, we隆炉ll always include <stdio.h> normally by including apue.h as this
// header contains the function prototypes for all the standard I/O functions.

makefile

mycat: mycat.c
	g++ -g -Wall mycat.c ../lib/libapue.a -I ../include -o mycat
clean:
	rm mycat

QZ%GVQHXDF954G9XWKWA$87

I624XASZ208YOZ5JS)CL1Q2

2d9f67ddf8230fc49567f7603ac3e5f2

131a68cdb61fceb569b924f006c749f5148d9933d60bdfdb9abb897bf9bd5ee8149f6d1ace7bfca72de0ac29cfaece60

730e0cf3d7ca7bcbe8acacdcbc096b63f724a86a59490a7045b9d7007e3c984254de11c162047bf2jw1ej8yw8wh8qj20m80xcanca5c27d1ed21b0ef4517c255fdfc451da81cb3e1ea8616e5fc48a219ec6aea14154e3a280 (1)a8616e5fc48a219ec6aea14154e3a280

ac908f81e582844d3a654a7aace21b39

ae51f3deb48f8c54c2ffcb2f38292df5e0fe7f85ae51f3deb48f8c54df24b63238292df5e0fe7f33aecca7d3bc9cf622203e2d6feab26244

原文地址:https://www.cnblogs.com/sunyongjie1984/p/4257124.html