Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

154 StandardI/O Library Chapter 5


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

Figure 5.4Copy standardinput to standardoutput usinggetcandputc

We can make another version of this program that usesfgetcandfputc,which
should be functions, not macros. (Wedon’t show this trivial change to the source code.)
Finally, we have a version that reads and writes lines, shown in Figure5.5.

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

Figure 5.5 Copy standardinput to standardoutput usingfgetsandfputs

Note that we do not close the standardI/O streams explicitly in either Figure5.4 or
Figure5.5. Instead, we know that theexitfunction will flush any unwritten data and
then close all open streams. (We’ll discuss this in Section 8.5.) It is interesting to
comparethe timing of these three programs with the timing data from Figure3.6. We
show this data when operating on the same file (98.5 MB with 3 million lines) in
Figure5.6.
For each of the three standardI/O versions, the user CPU time is larger than the
best read version from Figure3.6, because the character-at-a-time standardI/O
versions have a loop that is executed 100 million times, and the loop in the line-at-a-
Free download pdf