可变参数函数

来源:互联网 发布:叁度装饰预算软件 编辑:程序博客网 时间:2024/06/04 19:47
#include <stdarg.h>int iVar = 0;char cVar = '';/* Call MyPrintf */MyPrintf("Myprintf test %d, %c", iVar, cVar);unsigned int MyPrintf(char *pchFormat, ... ){    /* Get Argument Number */    unsigned int uiArgNum = 0;    uiArgNum = CountArgNum(pchFormat);    if(NULL == pchFormat)    {        return ERROR;    }        /* Get Argument Into Array */    int iArrArg[10];    va_list vaArgList;                                         /* declare argument list: vaArgList */    va_start(vaArgList, pchFormat);                    /* point vaArgList to the  first argument */    unsigned int i = 0;    while(i < uiArgNum)    {        iArrArg[i] = va_arg(vaArgList, int);           /* get one argument from vaArgList into iArrArg */        i++;    }    va_end(vaArgList);                                     /* set vaArgList to NULL  */    /* Printf Case Argument Number */    switch(uiArgNum)    {    case 0:            printf(pchFormat);            fprintf(pfLog, pchFormat);            break;    case 1:            printf(pchFormat, iArrArg[0]);            fprintf(pfLog, pchFormat, iArrArg[0]);            break;    case 2:            printf(pchFormat, iArrArg[0], iArrArg[1]);            fprintf(pfLog, pchFormat, iArrArg[0], iArrArg[1]);            break;    case 3:            printf(pchFormat, iArrArg[0], iArrArg[1], iArrArg[2]);            fprintf(pfLog, pchFormat, iArrArg[0], iArrArg[1], iArrArg[2]);            break;    default:            break;    }    return OK;}unsigned int CountArgNum(char *pchFormat){    /* parse string */    return uiArgNum;}

原创粉丝点击