Shihab Shihab - 1 month ago 17
C Question

function arguments like printf in c

I want to implement a function MyPrintf() that takes arguments like printf().
Now i am doing this by

sprintf(demoString,"Num=%d String=%s",num,str);
Myprintf(demoString);


I want to replace this function call as

Myprintf("Num=%d String=%s",num,str);


how this possible?

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

extern int Myprintf(const char *fmt, ...);

int Myprintf(const char *fmt, ...)
{
    char buffer[4096];
    va_list args;
    va_start(args, fmt);
    int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
    va_end(args);
    ...print the formatted buffer...
    return rc;
}

It isn't clear from your question exactly how the output is done; your existing Myprintf() presumably outputs it somewhere, maybe with fprintf(). If that's the case, you might write instead:

int Myprintf(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    int rc = vfprintf(debug_fp, fmt, args);
    va_end(args);
    return rc;
}

If you don't want to use the return value, declare the function as void and don't bother with the variable rc.

This is a fairly common pattern for 'printf() cover functions'.

Comments