gpt4 book ai didi

c - 在Windows上使用C语言读取硬盘上的特定扇区

转载 作者:可可西里 更新时间:2023-11-01 11:51:12 25 4
gpt4 key购买 nike

我已经尝试过这段代码,它在我从 USB 闪存驱动器读取一个扇区时有效,但它不适用于硬盘驱动器上的任何分区,所以我想知道当您尝试从 USB 读取时它是否相同或者从硬盘驱动器

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\n");
}
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 字节,并且进程以管理员权限运行。)

您还错误地检查了故障; CreateFile 在失败时返回 INVALID_HANDLE_VALUE 而不是 NULL

我成功测试了这段代码:

#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\n", GetLastError());
return 1;
}

SetFilePointer (device, numSector*512, NULL, FILE_BEGIN) ;

if (!ReadFile(device, sector, 512, &bytesRead, NULL))
{
printf("ReadFile: %u\n", GetLastError());
}
else
{
printf("Success!\n");
}

return 0;
}

关于c - 在Windows上使用C语言读取硬盘上的特定扇区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29219674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com