也就是在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,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);
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,fp);
fclose(fp);
DWORD dwLen;
WriteFile(hFile,NULL);
CloseHandle(hFile);
free(pBuffer);
}