利用可变参数打印log

// 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;
}

 

转载于:https://www.cnblogs.com/nanqiang/p/9015345.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值