读取unicode日志文件并清除记录的垃圾文件
//读取unicode文件,并清除记录的垃圾文件 //参数1:日志文件路径 bool ReadFilePath(const wchar_t *DataFilePath) { wchar_t ChBuffer = L'\0'; //将要从文件读取的单个字符 wchar_t CleanFilePath[256] = L"\0"; //将要清除的垃圾文件路径 DWORD ReadNumber = 0; //已经读取的路径拥有的字符数量 DWORD dwReadSize = 100;//已经读取多少数据 HANDLE handle_File = CreateFile(DataFilePath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); while(ReadFile(handle_File,&ChBuffer,2,&dwReadSize,NULL)) { if(dwReadSize == 0) { wprintf(L"检测到文件结尾\n"); break; } if(ChBuffer == L'\r') continue; if(ChBuffer == L'\n') { CleanFilePath[ReadNumber] = L'\0'; wprintf(L"已清除%s\n",CleanFilePath); DeleteFile(CleanFilePath); ReadNumber = 0; } else CleanFilePath[ReadNumber++] = ChBuffer; } // 释放文件对象资源 CloseHandle(handle_File) ; }
一开始因为不了解,使用了_wfopen_s,fgetwc系列函数,结果遇到了unicode文本乱码bug
然后通过,谷歌,msdn了解了,CreateFile,和ReadFile函数
使用CreateFile获取句柄,ReadFile读取文本中单个字符,并判断参数&dwReadSize是否为0来检测是否到了文件结尾
BOOL WINAPI ReadFile( _In_ HANDLE hFile, //文件句柄 _Out_ LPVOID lpBuffer, //读写缓冲区 _In_ DWORD nNumberOfBytesToRead, //读取多少数据 _Out_opt_ LPDWORD lpNumberOfBytesRead,//已经读取了多少数据 _Inout_opt_ LPOVERLAPPED lpOverlapped//异步读取结构 ); HANDLE hFile 文件句柄,通过CreateFile来获得 LPVOID lpBuffer 保存读取的字符 DWORD nNumberOfBytesToRead,一个wchar_t字符为2个数据 LPDWORD lpNumberOfBytesRead, 为0时为文件结尾 LPOVERLAPPED lpOverlapped //一般为空