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

本文展示了一个在Windows环境下使用C语言读取特定文件并解析数据的示例代码。通过调用Windows API函数CreateFile、ReadFile和CloseHandle,演示了如何打开、读取和关闭文件,以及如何解析读取到的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <windows.h>
#include <stdio.h>

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<bytesreaded;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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值