Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 1.5 Input and Output 9


#include "apue.h"
#define BUFFSIZE 4096
int
main(void)
{
int n;
char buf[BUFFSIZE];
while ((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0)
if (write(STDOUT_FILENO, buf, n) != n)
err_sys("write error");
if (n < 0)
err_sys("read error");
exit(0);
}

Figure 1.4Copy standardinput to standardoutput

The<unistd.h>header,included byapue.h,and the two constantsSTDIN_FILENO
andSTDOUT_FILENOarepart of the POSIX standard(about which we’ll have a lot
more to say in the next chapter). This header contains function prototypes for many of
the UNIX system services, such as thereadandwritefunctions that we call.
The constantsSTDIN_FILENOandSTDOUT_FILENOaredefined in<unistd.h>
and specify the file descriptors for standardinput and standardoutput. These values
are0and 1, respectively, as required by POSIX.1, but we’ll use the names for readability.
In Section 3.9, we’ll examine theBUFFSIZEconstant in detail, seeing how various
values affect the efficiency of the program. Regardless of the value of this constant,
however,this program still copies any regular file.
Thereadfunction returns the number of bytes that areread, 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,readreturns−1. Most of the
system functions return−1when an error occurs.
If we compile the program into the standardname (a.out)and execute it as
./a.out > data
standardinput is the terminal, standardoutput is redirected to the filedata,and
standarderror is also the terminal. If this output file doesn’t exist, the shell creates it by
default. The program copies lines that we type to the standardoutput until we type the
end-of-file character (usually Control-D).
If we run
./a.out < infile > outfile
then the file namedinfilewill be copied to the file namedoutfile.

In Chapter 3, we describe the unbuffered I/O functions in moredetail.
Free download pdf