这里先记录一下文件读取的常用函数的Sample,便于简单场合的快速翻阅
// FileReader.cpp : Defines the entry point for the console application.
//
#include “stdafx.h”
void MessageBoxLastError(TCHAR* caller)
{
TCHAR szBuf[64*1024];
LPVOID lpMsgBuf;
DWORD dw = GetLastError();
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
wsprintf(szBuf, TEXT(“%s failed with error %d: %s”), caller, dw, lpMsgBuf);
MessageBox(NULL, szBuf, TEXT(“Error”), MB_OK);
}
int _tmain(int argc, _TCHAR* argv[])
{
TCHAR* filename = TEXT(“E:\amu.mp3”);
HANDLE hFile = INVALID_HANDLE_VALUE;
hFile = CreateFile(filename,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
MessageBoxLastError(TEXT(“CreateFile”));
}
else
{
DWORD nBytesToRead = 1024000;
DWORD nBytesRead = 0;
BOOL bReadResult = FALSE;
ULONG nReadCount = 0;
BYTE* lpBuffer = new BYTE[nBytesToRead];
while(1)
{
bReadResult = ReadFile(hFile, lpBuffer, nBytesToRead, &nBytesRead, NULL);
nReadCount++;
if (bReadResult && nBytesRead == 0)
{
break;
}
}
if (lpBuffer)
{
delete [] lpBuffer;
lpBuffer = NULL;
}
}
if (CloseHandle(hFile) == 0)
{
MessageBoxLastError(TEXT(“CloseHandle(hFile)”));
}
return 0;
}