Basic and Advance C Question:
Download Questions PDF

How can I write a function that takes a format string and a variable number of arguments

Answer:

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. 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"); }

Download C Programming Interview Questions And Answers PDF

Previous QuestionNext Question
How can I write a function analogous to scanfI had a frustrating problem which turned out to be caused by the line