// ConsoleApplication1.cpp: 定义控制台应用程序的入口点。 // #pragma once #include <string> #include <Windows.h> #include <stdio.h> #include "stdafx.h" #include <stdarg.h> #include <stdlib.h> #include <cstring> using namespace std; const char* g_path = "C:\\test.log"; /* string GetTime() { SYSTEMTIME st; ::GetLocalTime(&st); char szTime[26] = { 0 }; sprintf_s(szTime, "%04d-%02d-%02d %02d:%02d:%02d %d ", \ st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); return szTime; } */ int myfprintf(const char* pFileName, const char* pFunName, const long lLine, const char* fmt, ...) { int ret = 0; //va_list是一个字符串指针,用于获取不确定个数的参数 va_list args; //读取可变参数的过程其实就是在堆栈中,使用指针,遍历堆栈段中 //的参数列表,从低地址到高地址一个一个的把参数内容读出来的过程 va_start(args, fmt); //该函数会根据参数fmt字符串来转换格式并格式化数据,然后将结果输出到参数Stream指定的文件中 //直到出现字符串结束的\0为止。 FILE* fp = NULL; fopen_s(&fp, g_path,"a+"); //string strTime = GetTime(); //fprintf(fp,"%s ", strTime.c_str());
int nFileNameLen = strlen(pFileName);
char szLine[10] = { 0 };
sprintf(szLine, "%ld", lLine);
int nLineLen = strlen(szLine);
int nSpaceLen = 30 - nFileNameLen - nLineLen;
for (int i = 0; i<nSpaceLen; ++i)
fwrite(" ", 1, 1, fp);
fprintf(fp,"%s:%ld ", pFileName, lLine);
ret = vfprintf(fp, fmt, args); printf("%d\n",ret); //获取完所有参数之后,为了避免发生程序瘫痪,需要将 ap指针关闭,其实这个函数相当于将args设置为NULL va_end(args); fflush(fp); fclose(fp); return ret; } #define LOG(fmt, ...) myfprintf(__FILE__, __FUNCTION__, __LINE__, fmt,##__VA_ARGS__) int main(void) { char test1[] = "aaaaaaaaaa"; char* p = test1; long test2 = 13333; long long test3 = 3333333333; LOG("test1 is:%s test2 is:%d test3 is:%lld\n ",p,test2,test3); LOG("test1 is:%s test2 is:%d test3 is:%lld\n ", p, test2, test3); getchar(); return 0; }