您的位置:首页 > 其它

18、通过可变参数实现打印日志

2010-12-06 21:31 330 查看
在c和c++中,可变参数使用的最多函数有:scanf,printf,以及fprintf,fscanf,sprintf等,MFC也提供CString::Format实现可变参数。

本示例通过va_list来实现自己的可变参数函数,实现程序写日志功能。

C++ version 2

// AssistTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "cstdio"
#include "iostream"
#include "string"
#include "fstream"
#include "cstdarg"
#include "windows.h"

using namespace std;

const int OP_SUCCESS = 0;
const int OP_FAILED = -1;
static string TestIT_MODULE = "TestItMe";

class mt
{
public:
void LogRecord(string strFunc, unsigned int uiLine, string strMod, int iulErrCode, char* cFormat, ...);
//print log module
};

void mt::LogRecord(string strFunc,
unsigned int uiLine,
string strMod,
int iErrCode,
char* cFormat,
...)
{
string strLog;
strLog.clear();
char acBuffer1[255], acBuffer2[255];
sprintf_s(acBuffer1, 254, "[%s] [%d] [%s] [%d] ", strFunc.data(), uiLine, strMod.data(), iErrCode);
va_list args;
va_start (args, cFormat);
vsprintf(acBuffer2,cFormat, args);

ofstream ofLogFile;
ofLogFile.open("F:\\log.txt", ios::out | ios::app);
if (!ofLogFile)
{
return;
}

string strBuffer1, strBuffer2;
strBuffer1 = acBuffer1;
strBuffer2 = acBuffer2;

ofLogFile.write(strBuffer1.data(), strBuffer1.size());
ofLogFile.write(strBuffer2.data(), strBuffer2.size());
ofLogFile.put('\n');
ofLogFile.close();

va_end(args);
}

int main(int argc, char* argv[])
{
string strFileName = "C:\\Intel\\Logs";
mt m1;
m1.LogRecord(__FUNCTION__, __LINE__ ,TestIT_MODULE, -1, "GetFile %s Attributes fail error code %d", strFileName.data(), GetLastError());
}


参考

[1] http://www.cplusplus.com/reference/clibrary/cstdio/vsprintf/

[2] /article/5663712.html

[3] /article/4743240.html

讲述了了va_start等可变参数的基本概念及定义
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: