windows下寫日誌文件的代碼

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()函數即可。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章