Actually i am trying to write my own printf() in c by using varags. But i am not getting the correct solution for this. can any one help me out
If you have some time and are really curious you could study the GNU libc's version: See printf, which in turn uses vprintf, which uses vfprintf
Linux va_start(3) man page gives very good example of writing such functions (much more simpler but in general all the major bricks are there). Also you could examine almost any libstdc implementation.
There are at least two books with good explanations of how a printf()
-like formatting function can be written (and complete working examples):
- Plauger, 'The Standard C Library'
- Hanson, 'C Interfaces and Implementations'
This answer may help you to understand how to write variadic functions. Note, no error / bounds checking is done, no attributes are set to tell the compiler what kind of arguments might be suitable, no benefit over just using printf() is achieved.
It may or may not be the example you are looking for.
The relevant snippet (expanded a bit here):
#include <stdarg.h>
void _printf(FILE *out, va_list ap)
{
vfprintf(out, fmt, ap);
}
void printf(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
_printf(stdout, ap);
va_end(ap);
}
Note: making these return the correct type (signed integer) is left as an exercise for the reader. This looks a lot like homework to me, I'm just trying to get you past any sticking point of using va_start and va_end, plus showing that a va_list can be passed to helper functions to avoid duplicating code in so many implementations of almost the same thing.
I strongly advise looking at the BSD (or even glibc) printf sub system implementation. You could also look at uclibc, dietlibc, etc ..