C++程序调试输出并写入文件(Linux/Windows)



#include "DebugOut.h"

DebugOut::DebugOut()
{
	m_sFilePath = NULL;
}

DebugOut::DebugOut(char* sFilePath)
{
	m_sFilePath = sFilePath;
}

DebugOut::~DebugOut()
{
	
}


/************************************************************************/
/* 功能描述:把调试信息写入到文件中                                     */
/* 参数说明:                                                           */
/*           sFilePath:文件保存路径                                    */
/*           sInfo    :待写入文件中的调试信息                          */
/* 返回值 :                                                            */
/*           0:失败                                                    */
/*           1:成功                                                    */
/************************************************************************/
int DebugOut::WriteToFile(const char* sFilePath, const char* sInfo)
{
	if (sFilePath == NULL)
	{
		return 0;
	}

	if (strcmp(sFilePath, "") == 0)
	{
		return 0;
	}

	FileRename(sFilePath);

	FILE* fp = fopen(sFilePath, "a+");
	if (fp == NULL)
	{
		return -1;
	}
	fwrite(sInfo, strlen(sInfo+1), 1, fp);
	fclose(fp);
	return 0;
}


/************************************************************************/
/* 功能描述:从文件路径中解析出文件保存目录、文件名、文件后缀、文件长度 */
/* 参数说明:                                                           */
/*           sFilePath:文件绝对路径                                    */
/*           sDir     :文件所存目录                                    */
/*           sFileName:文件名                                          */
/*           sSufix   :文件后缀                                        */
/*           iFileLen :文件长度(字节)                                */
/* 返回值 :                                                            */
/*           0:失败                                                    */
/*           1:成功                                                    */
/************************************************************************/
int DebugOut::FilePathParse(const char* sFilePath, char* sDir, char* sFileName, char* sSufix, int* iFileLen)
{
	//获取文件大小(字节)
	FILE* fp = fopen(sFilePath, "a+");
	if (fp == NULL)
	{
		return 0;
	}
	fseek(fp, 0L, SEEK_END);
	*iFileLen = ftell(fp);
	fclose(fp);


	//获取文件
	int iLen = strlen(sFilePath);
	int iPos = -1;
	for (int i=0; i<iLen; i++)
	{
		if ((sFilePath[i] == '\\') || (sFilePath[i] == '/'))
		{
			iPos = i;
		}
	}
	char strFile[256] = {0};
	int j = 0;
	for (int i=iPos+1; i<iLen; i++)
	{
		strFile[j++] = sFilePath[i];
	}
	strFile[j] = '\0';

	//获取文件所在目录
	if (iPos >= 0)
	{
		int k = 0;
		for (int i=0; i<=iPos; i++)
		{
			sDir[k++] = sFilePath[i];
		}
		sDir[k] = '\0';
	}
	
	//获取文件名
	int k = 0;
	for (unsigned int i=0; i<strlen(strFile); i++)
	{
		if (strFile[i] == '.')
		{
			k = i;
			sFileName[i] = '\0';
			break;
		} 
		else 
		{
			sFileName[i] = strFile[i];
		}
	}

	//获取文件后缀
	if(k > 0)
	{
		int j = 0;
		for (unsigned int i=k+1; i< strlen(strFile) ; i++)
		{
			sSufix[j++] = strFile[i];
		}
		sSufix[j] = '\0';
	}
	
	return 1;
}


/************************************************************************/
/* 功能描述:当文件大小超出指定大小时重命名文件                         */
/* 参数说明:                                                           */
/*           sFilePath:文件保存路径                                    */
/* 返回值 :                                                            */
/*           0:失败                                                    */
/*           1:成功                                                    */
/************************************************************************/
int DebugOut::FileRename(const char* sFilePath)
{
	int  iFileLen       = 0;
	char sFileName[256] = {0};
	char sDir[256]      = {0};
	char sSufix[256]    = {0};

	if(0 == FilePathParse(sFilePath, sDir, sFileName, sSufix, &iFileLen))
	{
		return 0;
	}	

	if (iFileLen > MAXLEN)
	{
		char tmpPath[256] = {0};
#if (OS_TYPE == Windows_OS)
		int i = 0;
		struct _finddata_t FileInfo;

		while (1)
		{
			sprintf(tmpPath, "%s%s_%d.%s", sDir, sFileName, i++, sSufix);
			if(_findfirst(tmpPath, &FileInfo) == -1L)
			{
				break;
			}
		}
#endif

#if (OS_TYPE == Linux_OS)
		struct dirent *dp = NULL;
		DIR *pDir = opendir(sDir);
		char allFileName[4096] = {0};
		while((dp = readdir(pDir)) != NULL)
		{
			strcat(allFileName, "$");
			strcat(allFileName, dp->d_name);				
		}

		char tmpName[32] = {0};	
		int i = 0;	
		while(1)
		{			
			sprintf(tmpName, "%s_%d.%s", sFileName, i++, sSufix);
			if(NULL == strstr(allFileName, tmpName))
			{
				break;
			}
		}
		strcpy(tmpPath, sDir);
		strcat(tmpPath, tmpName);
#endif
		if(-1 == rename(sFilePath, tmpPath))
		{
			printf("rename failed. error code:%d, error message:%s\n", errno, strerror(errno));
			return 0;
		}
	}

	return 1;
}


/************************************************************************/
/* 功能描述:获取当前时间                                               */
/* 参数说明:无                                                         */
/* 返回值  :返回当前时间                                               */
/************************************************************************/
char* DebugOut::GetCurrentTime() 
{
	char* strTime = (char*)malloc(32);
	memset(strTime, 0, 32);

	time_t timeTmp;
	time(&timeTmp);
	struct tm *ptm = localtime(&timeTmp);	
	struct tm *ptm2 = (struct tm *)malloc(sizeof(struct tm));
	memset(ptm2, 0, sizeof(struct tm));
	memcpy(ptm2, ptm, sizeof(struct tm));	
	sprintf(strTime, "[%04d-%02d-%02d %02d:%02d:%02d] ", (1900+ptm2->tm_year), (1+ptm2->tm_mon), ptm2->tm_mday, ptm2->tm_hour, ptm2->tm_min, ptm2->tm_sec);
	free(ptm2);
	ptm2 = NULL;
	return strTime;
}


/************************************************************************/
/* 功能描述:格式化打印输出,并写入文件                                 */
/* 参数说明:变参                                                       */
/* 返回值  :无                                                         */
/************************************************************************/
void DebugOut::Printf(const char *fmt, ...)
{
	char* buf = (char*)malloc(40960);
	memset(buf, 0, 40960);
	va_list args;	
	va_start(args, fmt);
	vsnprintf(buf, 4096, fmt, args);
	va_end(args);
	
	char* sTime = GetCurrentTime();

	char* sTmp = (char*)malloc(41000);
	memset(sTmp, 0, 41000);
	strcpy(sTmp, sTime);
	strcat(sTmp, buf);

#ifdef _DEBUG
	puts(sTmp);
#endif

	strcat(sTmp, "\n\r");
	WriteToFile(m_sFilePath, sTmp);

	free(sTime);
	sTime = NULL;
	free(buf);
	buf = NULL;
	free(sTmp);
	sTmp = NULL;
}
#ifndef __DEBUGOUTTOFILE__
#define __DEBUGOUTTOFILE__


#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
#include <stdarg.h>

#define Windows_OS 1
#define Linux_OS   2

#define OS_TYPE 2

#if (OS_TYPE == Windows_OS)
#include <io.h>
#endif

#if (OS_TYPE == Linux_OS)
#include <dirent.h>
#include <errno.h>
#define _DEBUG
#endif

//#define MAXLEN 4194304
#define MAXLEN 128

class DebugOut
{
public:
	DebugOut();
	DebugOut(char* sFilePath);
	~DebugOut();
	void Printf(const char *fmt, ...);

private:
	char* GetCurrentTime();
	int WriteToFile(const char* sFilePath, const char* sInfo);
	int FilePathParse(const char* sFilePath, char* sDir, char* sFileName, char* sSufix, int* iFileLen);
	int FileRename(const char* sFilePath);

	char* m_sFilePath;
};


#endif

#include "DebugOut.h"

int main()
{
	DebugOut* debugOut = new DebugOut((char *)"/root/test.txt");
	
	debugOut->Printf("%s %s %d", __FILE__, __FUNCTION__, __LINE__);
	debugOut->Printf("%s %s %d", __FILE__, __FUNCTION__, __LINE__);
	
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值