C语言 C++ MFC 写日志到文件

C语言 写日志到文件

#include <stdio.h>
#include <time.h>
int WriteLogToFile2(char* szLog) {
    
    
	// 打开一个文件用于写入日志
	FILE* logfile;
	fopen_s(&logfile, ".\\SmartPayDemo.log", "a"); // "a"表示追加模式,如果文件不存在则创建

	if (logfile == NULL) {
    
    
		printf("Can not open log file.\n");
		return 1;
	}

	time_t current_time;
	struct tm time_info;
	char time_string[20];

	time(&current_time);
	if (localtime_s(&time_info, &current_time) != 0) {
    
    
		printf("Unable to retrieve local time.\n");
		fclose(logfile);
		return 1;
	}
	strftime(time_string, sizeof(time_string), "%Y-%m-%d %H:%M:%S", &time_info);

	// 写入日志消息到文件
	fprintf(logfile, "[%s] %s\n", time_string, szLog);

	// 关闭文件
	fclose(logfile);
	return 0;
}
void CSmartPayDemoDlg::PrintLog(const char* msg, ...)
{
    
    
	//CString strAll = TEXT("");
	//((CEdit*)GetDlgItem(IDC_EDIT1))->GetWindowTextW(strAll);
	//((CEdit*)GetDlgItem(IDC_EDIT1))->SetWindowTextW(strAll + strAdd + L"\r\n");
	char sMsgBuff[4096] = {
    
     0 };
	va_list args;
	va_start(args, msg);
	vsprintf_s(sMsgBuff, msg, args);
	va_end(args);
	//OutputDebugStringA(sMsgBuff);
	WriteLogToFile2(sMsgBuff);
	((CEdit*)GetDlgItem(IDC_EDIT1))->SetSel(GetDlgItem(IDC_EDIT1)->GetWindowTextLength(), GetDlgItem(IDC_EDIT1)->GetWindowTextLength());
	((CEdit*)GetDlgItem(IDC_EDIT1))->ReplaceSel(CString(sMsgBuff) + L"\r\n");
}

猜你喜欢

转载自blog.csdn.net/chenhao0568/article/details/132870969