使用CreateFile, ReadFile, WriteFile在Windows NT/2000/XP下读写绝对扇区的方法

王朝system·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

也就是在CreateFile的时候打开文件名指定: “\\.\Device”就可以了.

因为代码比较短, 所以我不做注释, 相信大家看代码就能明白意思了.

另外这里读写的都是软盘A盘第0扇区, 如果想读写其他的扇区, 那么可以使用API SetFilePointer.

读扇区的方法(下面的代码演示从A盘的第0扇区读出数据, 写入到文件BOOT.BIN中):

#include <windows.h>

#include <assert.h>

#include <stdio.h>

void main()

{

HANDLE hFile;

hFile = CreateFile("\\\\.\\A:",

GENERIC_READ,

FILE_SHARE_READ,

NULL,

OPEN_EXISTING,

0,

NULL);

assert(hFile && "CreateFile failed!");

PBYTE pBuffer = (PBYTE)malloc(512);

assert(pBuffer && "Allocate memory failed!");

DWORD dwLen;

ReadFile(hFile, pBuffer, 512, &dwLen, NULL);

FILE * fp;

fp = fopen("boot.bin", "wb");

assert(fp && "Open file failed!");

fwrite(pBuffer, 512, 1, fp);

fclose(fp);

CloseHandle(hFile);

free(pBuffer);

}

那么相应的, 写扇区的方法的就是这样的咯(以下代码演示从BOOT.BIN中读出数据写入到A盘第0扇区):

#include <windows.h>

#include <assert.h>

#include <stdio.h>

void main()

{

HANDLE hFile;

hFile = CreateFile("\\\\.\\A:",

GENERIC_WRITE,

FILE_SHARE_WRITE,

NULL,

OPEN_EXISTING,

0,

NULL);

assert(hFile && "CreateFile failed!");

PBYTE pBuffer = (PBYTE)malloc(512);

assert(pBuffer && "Allocate memory failed!");

FILE * fp;

fp = fopen("boot.bin", "rb");

assert(fp && "Open file failed!");

fread(pBuffer, 512, 1, fp);

fclose(fp);

DWORD dwLen;

WriteFile(hFile, pBuffer, 512, &dwLen, NULL);

CloseHandle(hFile);

free(pBuffer);

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航