有时候程序总是会发生意想不到的情况,为了方便排查错误的情况,还是写日志比较方便。这里自己写了一个简单的函数,能实现基本的功能。
BOOL WriteLog(char * DataBuffer) {
CString strTempPath;
::GetTempPath(MAX_PATH, strTempPath.GetBuffer(MAX_PATH));
CString strLogFile = strTempPath + L"Log.txt";
HANDLE hFile = INVALID_HANDLE_VALUE;
DWORD dwBytesWritten = ;
BOOL bErrorFlag = FALSE;
OVERLAPPED strOverlapped = {};
strOverlapped.Offset = 0xFFFFFFFF;
strOverlapped.OffsetHigh= 0xFFFFFFFF;
hFile = CreateFile(strLogFile, GENERIC_READ| GENERIC_WRITE, , NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile== INVALID_HANDLE_VALUE)
{
return false;
}
char TimeMessage[MAX_PATH] = { };
SYSTEMTIME st;
::GetLocalTime(&st);
char szTime[] = { };
sprintf_s(szTime, "%04d-%02d-%02d %02d:%02d:%02d %d ", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
sprintf_s(TimeMessage, "%s: %s\n", szTime,DataBuffer);
DWORD dwBytesToWrite = (DWORD)strlen(TimeMessage);
bErrorFlag = WriteFile(hFile, TimeMessage, dwBytesToWrite, NULL, &strOverlapped);
if (bErrorFlag==FALSE)
{
return false;
}
CloseHandle(hFile);
return true;
}
这里用到CreateFile和WriteFile函数:
CreateFile 函数创建或打开下列对象,并返回一个可以用来访问这些对象的句柄。
文件
pipes
邮槽
通信资源
磁盘驱动器(仅适用于 windowsNT )
控制台
文件夹(仅用于打开)
HANDLE CreateFile(
LPCTSTR lpFileName, // 指向文件名的指针
DWORD dwDesiredAccess, // 访问模式(写 / 读)
DWORD dwShareMode, // 共享模式
LPSECURITY_ATTRIBUTES lpSecurityAttributes, // 指向安全属性的指针
DWORD dwCreationDisposition, // 如何创建
DWORD dwFlagsAndAttributes, // 文件属性
HANDLE hTemplateFile // 用于复制文件句柄
);
BOOL WriteFile(
HANDLE hFile,
LPCVOID lpBuffer,
DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten,
LPOVERLAPPED lpOverlapped
);
这里有一点需要说明的,要写让文件能追加改写,一定要定义一个 OVERLAPPED 结构体,并把offset,offsethigh设成0xFFFFFFFF,并把这个结构体的地址传给WriteFile的最后一个参数。不然每次都会重头写,
OVERLAPPED strOverlapped = {};
strOverlapped.Offset = 0xFFFFFFFF;
strOverlapped.OffsetHigh= 0xFFFFFFFF;
bErrorFlag = WriteFile(hFile, TimeMessage, dwBytesToWrite, NULL, &strOverlapped);
这里有一个获得time的函数,也值得关注。
SYSTEMTIME st;
::GetLocalTime(&st);
char szTime[26] = { 0 };
sprintf_s(szTime, "%04d-%02d-%02d %02d:%02d:%02d %d ", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds)
最后的结果类似这样的: