c/c++ printf格式化打印

简单化的(Linux下使用):

const char* mygetFileName(char* szPath);
#if (1)
#define FENG_(fmt, arg...) printf("[Feng] [%s]<%s:%u> :" fmt"\n",mygetFileName(__FILE__), __FUNCTION__, __LINE__, ##arg);
#else
#define FENG_(fmt, arg...)
#endif
static char g_stFunc[32];
const char* mygetFileName(char* szPath)
{
	memset(g_stFunc,0,32);
	char szTmp[256];
	sprintf(szTmp,"%s",szPath);
	std::string s(szTmp);
	int pos = s.find_last_of('/');
	memcpy(g_stFunc,s.substr(pos+1).c_str(),31);
	return  g_stFunc;
}

int main()
{
	FENG_("Test");
}

复杂一点的,把时间信息也打印出来的(支持win32和Linux)

#include <stdint.h>
#include <stdio.h>
#include <string.h>

#ifdef _WIN32
#include <time.h>
#include<windows.h>
#else
#include <sys/time.h>
#include <unistd.h>
#endif

char *gdbg_getDomain(char* file) {
	static char domain[32] = { 0 };
	char *pS = strrchr(file, '/');
	if (0 == pS) {
		pS = strrchr(file, '\\');
	}
	pS += 1;
	char *pE = strrchr((char*)file, '.');
	if (0 != pS && 0 != pE && (uint64_t)(pE - pS)<sizeof(domain)) {
		domain[pE - pS] = 0;
		memcpy(domain, pS, pE - pS);
	}
	return domain;
}

char *gdbg_debugtimer(char *p)
{

	static char _buf[32] = { 0 };
	if (0 == p) {
		p = _buf;
	}
#ifdef _WIN32
	SYSTEMTIME currentTime;
	GetLocalTime(&currentTime);
	tm temptm = { currentTime.wSecond,
		currentTime.wMinute,
		currentTime.wHour,
		currentTime.wDay,
		currentTime.wMonth - 1,
		currentTime.wYear - 1900
	};

	sprintf(p, "[%02d:%02d:%02d.%06ld] ", currentTime.wHour, currentTime.wMinute, currentTime.wSecond, currentTime.wMilliseconds);
#else
	struct timeval tp;
	gettimeofday(&tp, NULL);
	time_t now;
	struct tm *tm_now;
	time(&now);
	tm_now = localtime(&now);
	sprintf(p, "[%02d:%02d:%02d.%06ld] ", tm_now->tm_hour, tm_now->tm_min, tm_now->tm_sec, tp.tv_usec);
#endif
	return p;
}


#define gdbg_printf(fmt, ...) \
    do { \
	printf("%s %s:%s:%d: " fmt"\n",gdbg_debugtimer(0),gdbg_getDomain((char*)__FILE__),__func__,__LINE__, ##__VA_ARGS__); \
	} while (0);

void TestFunc()
{
	gdbg_printf("TestFunc");
}

int main()
{
	gdbg_printf("Test");
	TestFunc();
}

格式:
[时间] 文件名:函数:行号:内容
输出结果

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值