使用Windows API读取文件数据的例子

#include
#include

int main(int argc,char** argv)
{
 HANDLE hFile;
 char* buffer;
 DWORD bytesreaded=0;
 UINT DataSize=8;
 //open file
 hFile=CreateFile("test.data",GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,
  FILE_ATTRIBUTE_READONLY,NULL);
 if(!hFile)
 {
  printf("Cann't open file \"test.data\"\n");
  return 1;
 }
 //create buffer
 buffer=(char*)LocalAlloc(LMEM_MOVEABLE|LMEM_ZEROINIT,16);
 if(!buffer)
 {
  printf("Cann't allocate memory!\n");
  return 2;
 }
 //read file
 if(!ReadFile(hFile,buffer,DataSize,&bytesreaded,NULL))
 {
  printf("Cann't read file!\n");
  return 3;
 }
 //close file
 CloseHandle(hFile);
 //print data
 printf("Total %d bytes!\n",bytesreaded);
 char hi,low;
 char data;
 printf("Data:\n");
 for(int i=0;i {
  data=*(buffer+i);
  hi=(data&0xF0)>>4;
  low=data&0x0F;
  printf("byte[%d]:",i);
  if(hi<10) printf("%c",hi+'0');
  else printf("%c",(hi-10)+'A');
  if(low<10) printf("%c",low+'0');
  else printf("%c",(low-10)+'A');
  printf("\n");
 }
 //free buffer
 LocalFree(buffer);
 printf("\n");
 return 0;
}

你可能感兴趣的:(c/c++)