5.8. Standard I/O EfficiencyUsing the functions from the previous section, we can get an idea of the efficiency of the standard I/O system. The program in Figure 3.4: it simply copies standard input to standard output, using getc and putc. These two routines can be implemented as macros. Figure 5.4. Copy standard input to standard output using getc and 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); } We can make another version of this program that uses fgetc and fputc, which should be functions, not macros. (We don't show this trivial change to the source code.)Finally, we have a version that reads and writes lines, shown in Figure 5.5. Figure 5.5. Copy standard input to standard output using fgets and 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); } Note that we do not close the standard I/O streams explicitly in Section 8.5.) It is interesting to compare the timing of these three programs with the timing data from Figure 3.5. We show this data when operating on the same file (98.5 MB with 3 million lines) in Figure 3.5 | 0.01 | 0.18 | 6.67 | |
fgets, fputs | 2.59 | 0.19 | 7.15 | 139 |
getc, putc | 10.84 | 0.27 | 12.07 | 120 |
fgetc, fputc | 10.44 | 0.27 | 11.42 | 120 |
single byte time from Figure 3.5 | 124.89 | 161.65 | 288.64 |