### Question 15.5

How can I write a function that takes a format string and a variable number of arguments, like `printf`, and passes them to `printf` to do most of the work?

Use `vprintf`, `vfprintf`, or `vsprintf`.

Here is an `error` routine which prints an error message, preceded by the string ``error: '' and terminated with a newline:

    #include <stdio.h>
    #include <stdarg.h>

    void error(char *fmt, ...)
    {
    	va_list argp;
    	fprintf(stderr, "error: ");
    	va_start(argp, fmt);
    	vfprintf(stderr, fmt, argp);
    	va_end(argp);
    	fprintf(stderr, "\n");
    }

See also question 15.7.

References: K&R2 Sec. 8.3 p. 174, Sec. B1.2 p. 245
ANSI Secs. 4.9.6.7,4.9.6.8,4.9.6.9
ISO Secs. 7.9.6.7,7.9.6.8,7.9.6.9
H&S Sec. 15.12 pp. 379-80
PCS Sec. 11 pp. 186-7

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback