This post is used to tell how to write your own function with varying arguments (如何写变参函数) – we will write our own ‘printf()’ function called ‘ddLog()’. Wish the code below would give you a hint:)
/*
* This source file is used to show an example on
* writing function with a varying number of arguments
* of varying types, like printf() and snprintf().
* Originated: Jan 12, 2011
* dave.tian@alcatel-lucent.com
*/
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
/* var arg function declaration */
int ddLog( const char *, …);
int main( void)
{
int date = 20110112;
char at = ‘@’;
ddLog( “This is a demo function”
” used to show how to write”
” var arg function based on”
” ANSI stylen”
“-%s%c%dn”,
“daveti”, at, date);
return 0;
}
/* ddLog() is some kind of like printf() */
int ddLog( const char *msg, …)
{
char outPut[ 1000];
char *outP = outPut;
// Var arg structure
va_list argS;
// Determine if it is format string
char *percentP = NULL;
// Pointer for each arg
char *argP;
char argChar;
int argInt;
// Start var arg parsing
va_start(argS, msg);
while ( *msg != ”)
{
if ( *msg == ‘%’)
{
percentP = msg;
msg++;
continue;
}
if ( percentP != NULL)
{
switch ( *msg)
{
case ‘s’: //string
argP = va_arg( argS, const char *);
outP += snprintf( outP, (1000+outPut-outP), “%s”, argP);
break;
case ‘c’: //char
argChar = (char) va_arg( argS, int);
outP += snprintf( outP, (1000+outPut-outP), “%c”, argChar);
break;
case ‘d’: //int
argInt = va_arg( argS, int);
outP += snprintf( outP, (1000+outPut-outP), “%d”, argInt);
break;
default:
// Un-supported format string
// Copy the ‘%’ and un-supported char here
*outP++ = ‘%’;
*outP++ = *msg;
break;
}
percentP = NULL;
msg++;
continue;
}
*outP++ = *msg++;
}
// Copy the ” at the end
*outP = ”;
// End var arg parsing
va_end(argS);
printf(“%s”, outPut);
return strlen( outPut);
}