wrapper printf function

R

rejeesh

Hi,

I need a 'wrapper' function for printf. So that anywhere in my program
if i call the wrapper function it does the same thing as the regular
printf function, but puts a custom message at the begining.

so here it goes :-

int my_printf ( <what do I put here> )
{
printf("This is My Header::");
printf( <Pass the arguments of the my_printf right here>);
}

and in some where in my main pgm files;

my_printf("This is a test %d, %x, %s.\n", 10, 10, "10");

should do exactly as printf does, except put "This is My Header::" at
the begining.

Please help!
Thanks
 
E

Eric Sosman

rejeesh said:
Hi,

I need a 'wrapper' function for printf. So that anywhere in my program
if i call the wrapper function it does the same thing as the regular
printf function, but puts a custom message at the begining.

so here it goes :-

int my_printf ( <what do I put here> )
{
printf("This is My Header::");
printf( <Pass the arguments of the my_printf right here>);
}

and in some where in my main pgm files;

my_printf("This is a test %d, %x, %s.\n", 10, 10, "10");

should do exactly as printf does, except put "This is My Header::" at
the begining.

#include <stdio.h>
#include <stdarg.h>
int my_printf(const char *format, ...) {
int res1, res2;
va_list ap;
res1 = printf("This is My Header::");
if (res1 < 0)
return res1;
va_start (ap, format);
res2 = vprintf(format, ap);
va_end (ap);
return (res2 < 0) ? res2 : res1 + res2;
}
 
B

Ben Pfaff

I need a 'wrapper' function for printf. So that anywhere in my program
if i call the wrapper function it does the same thing as the regular
printf function, but puts a custom message at the begining.

This is a FAQ.

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?

A: Use vprintf(), vfprintf(), or vsprintf().

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(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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top