windows下写日志文件的代码

本文介绍了日志文件创建、检查是否存在、日期时间格式化、日志内容保存及日志写入的基本方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

void CreateLogFile()
{
	ofstream file(LOG_FILE_PATH,ios::binary);
	file.close();
}

bool isLogFileExist()
{
	bool bRet = false;

	fstream file;
	file.open(LOG_FILE_PATH, ios::binary |ios::in);
	if(!file)
	{
		bRet = false;
	}
	else
	{
		bRet = true;
	}

	file.close();
	return bRet;
}

void SaveLogFile(CString csLog)
{
	ofstream file;
	file.open(LOG_FILE_PATH, ios::binary | ios::app);

	SYSTEMTIME st;
	GetLocalTime(&st);

	CString csYear;
	csYear.Format(_T("%4d"),st.wYear);
	CString csMonth;
	csMonth.Format(_T("%02d"),st.wMonth);
	CString csDay;
	csDay.Format(_T("%02d"),st.wDay);

	CString csHour;
	csHour.Format(_T("%02d"),st.wHour);
	CString csMinute;
	csMinute.Format(_T("%02d"),st.wMinute);
	CString csSecond;
	csSecond.Format(_T("%02d"),st.wSecond);

	CString strDate = csYear + _T("-") + csMonth +  _T("-") + csDay + _T(" ");
    CString strTime = csHour + _T(":") + csMinute + _T(":") + csSecond;

	CStringA straDate(strDate);
	file<<straDate;
	CStringA straTime(strTime);
	file<<straTime;

    file<<_T("  ");

	file<<csLog;

	file<<'\n';

	file.close();	
}

void WriteLogFile(CString csLogLine)
{
	bool bExist = isLogFileExist();

	if(!bExist)
	{
		CreateLogFile();
	}

	SaveLogFile(csLogLine);
}
只需调用WriteLogFile()函数即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值