This page has been designed specifically for the printed screen. It may look different than the page you were viewing on the web.
Please recycle it when you're done reading.

The URI for this page is { http://cc.byexamples.com }

va list, create function like printf Posted on January 18th

The printf function can have variable length of arguments pass into the function. Sometimes we might want to create a customized printf like function. Observed to the sample bellow:


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

char ErrStr[128];
char Status[128];
int flag=1;

void Feeder( char *buff,...)
{
    va_list arglist;

    va_start(arglist,buff);

    //customized operations...
    if (flag<0)
        vsprintf(ErrStr,buff,arglist);
    else if (flag>=0)
        vsprintf(Status,buff,arglist);

    va_end(arglist);
}

int main()
{
    Feeder("Hello World %d %f %s\n",5,5.55,"55.55");
    if(Status[0])
        printf("Result: %s\n",Status);

    return 0;
}

The Feeder function will take unlimited arguments like printf, in the function it determine the flag and copy the string with those arguments together to appropriate string using vspintf.

Output:

Result: Hello World 5 5.550000 55.55
Trackback URL

Some Responses to “va list, create function like printf” :

  1. [...] va list, create function like printf [...]

    Commented writing log files or config files uses fprintf on January 23rd, 2007.
  2. good

    Commented rert on July 12th, 2007.
Leave your own comments about this post: