Page 174

Rewrite the program cat from Chapter 7 using read, write, open and close instead of their standard library equivalents. Perform experiments to determine the relative speeds of the two versions.

#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <syscall.h>
#include <unistd.h>

void error(char *, ...);

int main(int argc, char *argv[])
{
	int ifd, ofd = 1;
	int n;
	char buf[BUFSIZ];

	while (--argc > 0) {
		if ((ifd = open(*++argv, O_RDONLY, 0)) < 0) {
			error("can't open %s", *argv);
		} else {
			while ((n = read(ifd, buf, BUFSIZ)) > 0) {
				if (write(ofd, buf, n) != n) {
					error("write error on file %s", *argv);
				}
			}
			close(ifd);
		}
	}
}

void error(char *fmt, ...)
{
	va_list args;

	va_start(args, fmt);
	fprintf(stderr, "error: ");
	vfprintf(stderr, fmt, args);
	fprintf(stderr, "\n");
	va_end(args);
	exit(1);
}