问题描述
我已经尝试过这段代码,当我从 USB 闪存驱动器读取扇区时它可以工作,但它不适用于硬盘驱动器上的任何分区,所以我想知道当你尝试从 USB 读取时它是否相同或从硬盘驱动器
i have tried this code it works when i read a sector from an USB flash drive but it does'nt work with any partiton on hard drive , so i want to know if it's the same thing when you try to read from usb or from hard drive
int ReadSector(int numSector,BYTE* buf){
int retCode = 0;
BYTE sector[512];
DWORD bytesRead;
HANDLE device = NULL;
device = CreateFile("\\.\H:", // Drive to open
GENERIC_READ, // Access mode
FILE_SHARE_READ, // Share Mode
NULL, // Security Descriptor
OPEN_EXISTING, // How to create
0, // File attributes
NULL); // Handle to template
if(device != NULL)
{
SetFilePointer (device, numSector*512, NULL, FILE_BEGIN) ;
if (!ReadFile(device, sector, 512, &bytesRead, NULL))
{
printf("Error in reading disk
");
}
else
{
// Copy boot sector into buffer and set retCode
memcpy(buf,sector, 512);
retCode=1;
}
CloseHandle(device);
// Close the handle
}
return retCode;}
推荐答案
问题是共享模式.你已经指定了 FILE_SHARE_READ
这意味着没有其他人被允许写入设备,但是分区已经被安装为读/写,所以不可能给你那种共享模式.如果您使用 FILE_SHARE_READ|FILE_SHARE_WRITE
它将起作用.(好吧,前提是磁盘扇区大小为 512 字节,并且进程以管理员权限运行.)
The problem is the sharing mode. You have specified FILE_SHARE_READ
which means that nobody else is allowed to write to the device, but the partition is already mounted read/write so it isn't possible to give you that sharing mode. If you use FILE_SHARE_READ|FILE_SHARE_WRITE
it will work. (Well, provided the disk sector size is 512 bytes, and provided the process is running with administrator privilege.)
您还错误地检查了失败;CreateFile 在失败时返回 INVALID_HANDLE_VALUE
而不是 NULL
.
You're also checking for failure incorrectly; CreateFile returns INVALID_HANDLE_VALUE
on failure rather than NULL
.
我成功测试了这段代码:
I tested this code successfully:
#include <windows.h>
#include <stdio.h>
int main(int argc, char ** argv)
{
int retCode = 0;
BYTE sector[512];
DWORD bytesRead;
HANDLE device = NULL;
int numSector = 5;
device = CreateFile(L"\\.\C:", // Drive to open
GENERIC_READ, // Access mode
FILE_SHARE_READ|FILE_SHARE_WRITE, // Share Mode
NULL, // Security Descriptor
OPEN_EXISTING, // How to create
0, // File attributes
NULL); // Handle to template
if(device == INVALID_HANDLE_VALUE)
{
printf("CreateFile: %u
", GetLastError());
return 1;
}
SetFilePointer (device, numSector*512, NULL, FILE_BEGIN) ;
if (!ReadFile(device, sector, 512, &bytesRead, NULL))
{
printf("ReadFile: %u
", GetLastError());
}
else
{
printf("Success!
");
}
return 0;
}
这篇关于在 Windows 上使用 C 语言读取硬盘上的特定扇区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!