Win32 Files API Sample

这里先记录一下文件读取的常用函数的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;
}

 

By Lu Jun

80后男,就职于软件行业。习于F*** GFW。人生48%时间陪同电子设备和互联网,美剧迷,高清视频狂热者,游戏菜鸟,长期谷粉,临时果粉,略知摄影。

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.