C语言 写日志到文件
#include <stdio.h>
#include <time.h>
int WriteLogToFile2(char* szLog) {
FILE* logfile;
fopen_s(&logfile, ".\\SmartPayDemo.log", "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(¤t_time);
if (localtime_s(&time_info, ¤t_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, ...)
{
char sMsgBuff[4096] = { 0 };
va_list args;
va_start(args, msg);
vsprintf_s(sMsgBuff, msg, args);
va_end(args);
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");
}