Skip to content

va list, create function like printf

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

Categories: Uncategorized.

Comment Feed

2 Responses

  1. good



Some HTML is OK

or, reply to this post via trackback.

Continuing the Discussion

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