也就是在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);
}
本文地址:http://com.8s8s.com/it/it28596.htm