8

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 is this possible?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Shihab
  • 531
  • 1
  • 12
  • 25
  • 2
    I guess this link is right for you: http://www.eskimo.com/~scs/cclass/int/sx11b.html – Jack Feb 08 '13 at 05:09

3 Answers3

14
#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'.

T-Bull
  • 2,136
  • 2
  • 15
  • 17
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1

You need to define a function with variable arguments, and use vsprintf to build the string.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Karthik T
  • 31,456
  • 5
  • 68
  • 87
1

The printf and its relatives are in a family of functions called variadic functions and there are macros/functions in the <stddef.h> header in the C standard library to manipulate variadic argument lists. Look at the GNU docs for examples: How Variadic Functions are Defined and Used.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
syazdani
  • 4,760
  • 1
  • 26
  • 35