在c和c++中,可變參數使用的最多函數有:scanf,printf,以及fprintf,fscanf,sprintf等,MFC也提供CString::Format實作可變參數。
本示例通過va_list來實作自己的可變參數函數,實作程式寫日志功能。

通過可變參數實作日志列印
// ForATest.cpp : 定義控制台應用程式的入口點。
#include "stdafx.h"
#include "Windows.h"
#include "iostream"
using namespace std;
#include "string"
#include <stdio.h>
#include <stdarg.h>
#define PL_ERROR -2
#define SERVICE_ERROR(strMod, ulErrCode, cFormat, ...) \
logRecord(__FUNCTION__, __LINE__, strMod, PL_ERROR, ulErrCode, cFormat, __VA_ARGS__);
static string TestIT_MODULE = "TestItMe";
void logRecord(string strFunc,
int iLine,
string strMod,
int iLevel,
int iErrCode,
char* cFormat,
...)
{
string strLog;
strLog.clear();
char acBuffer1[255], acBuffer2[255];
sprintf_s(acBuffer1, 254, "[%s] [%d] [%s] [%d] [%d]", strFunc.data(), iLine, strMod.data(), iLevel, iErrCode);
va_list args;
va_start (args, cFormat);
vsprintf(acBuffer2,cFormat, args);
FILE* pFile = fopen("C:\\log.txt","a+");
if (NULL == pFile)
return;
fprintf(pFile, acBuffer1);
fprintf(pFile, acBuffer2);
fprintf(pFile,"\n");
fclose(pFile);
va_end(args);
}
int _tmain(int argc, _TCHAR* argv[])
string strFileName = "C:\\Intel\\Logs";
SERVICE_ERROR(TestIT_MODULE, -1, "GetFile %s Attributes fail error code %d", strFileName.data(), GetLastError());

sprintf_s的一個示例
int main( void )
char buffer[200], s[] = "computer", c = 'l';
int i = 35, j;
float fp = 1.7320534f;
string name = "hello";
// Format and print various data:
j = sprintf_s( buffer, 200, " String: %s\n", s );
j += sprintf_s( buffer + j, 200 - j, " Character: %c\n", c );
j += sprintf_s( buffer + j, 200 - j, " Integer: %d\n", i );
j += sprintf_s( buffer + j, 200 - j, " Real: %f\n", fp );
j += sprintf_s( buffer + j, 200 - j, " Name: %s\n", name.data() );
printf_s( "Output:\n%s\ncharacter count = %d\n", buffer, j );

C++ version

C++ version 2
參考
講述了了va_start等可變參數的基本概念及定義