prev up next   top/contents search

comp.lang.c FAQ list · Question 15.5

Q: 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?


A: Use vprintf, vfprintf, or vsprintf. These routines are like their counterparts printf, fprintf, and sprintf, except that instead of a variable-length argument list, they accept a single va_list pointer.

As an example, here is an error function which prints an error message, preceded by the string ``error: '' and terminated with a newline:

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

void error(const 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
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


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North