(Windows)用C读取磁盘的引导部门
我正在尝试与C一起阅读磁盘的引导扇区。我计划修改代码以将其用于其他磁盘(例如USB闪存驱动器)。我尝试了此代码作为测试:
#include<stdio.h>
#include<unistd.h>
int main(){
FILE *fp;
char buf[512];
fp = fopen("\\\\.\\PhysicalDrive0", "rb");
int r = fread(buf, 1, 512, fp);
printf("Elements read: %s", r);
sleep(3);
fclose(fp);
return 0;
}
当我编译并运行它时,我会得到(字面意思)elements读取:( null)
。 如果我以管理员的身份运行它,则获得元素读取:
。
为什么我无法正确阅读引导扇区,如何修复代码?
使用MINGW GCC在Win10上运行。
I am trying to read the boot sector of my disk with C. I am planning to modify the code to use it for other disks such as USB flash drives. I tried this code as a test:
#include<stdio.h>
#include<unistd.h>
int main(){
FILE *fp;
char buf[512];
fp = fopen("\\\\.\\PhysicalDrive0", "rb");
int r = fread(buf, 1, 512, fp);
printf("Elements read: %s", r);
sleep(3);
fclose(fp);
return 0;
}
When I compile it and run it, I get (literally) Elements read: (null)
.
If I run it as administrator, I instead get Elements read:
.
Why am I not able to read the boot sector correctly, and how can I fix the code?
Running on Win10 with MinGW GCC.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,
r
是读取的字符数,您将其视为是C型字符串的指针。为了有机会工作,您需要将buf
而不是r
传递给您的printf
调用,或更改%s
to%d
因此,您要打印整数值,而不是试图将其视为字符串指针。失败的读取(当您缺乏权限时)返回0,printf
有助于显示为(null)
而不是segfaulting;成功的读取返回一个整数,当被视为指针时,指向垃圾地址可能几乎是可读的,但恰好只包含nul
字符,所以什么也没有打印。其次,假设您想查看数据,而不仅仅是读取字节的数量,赔率是启动扇区的
nul
nul 字符,这将导致%s
扫描假设字符串已经完成。如果要查看数据,请fwrite
它到其他文件进行检查,或者按字符进行编码,如十六进制,然后将其写入人类的stdout
阅读。First,
r
is the number of characters read, and you treated it like it was a pointer to a C-style string. To have even a chance of working, you'd need to passbuf
, notr
, to yourprintf
call, or change%s
to%d
so you're printing the integer value, not trying to treat it as a pointer to a string. The failed read (when you lack permissions) returns 0, whichprintf
helpfully displays as(null)
rather than segfaulting; the successful read returns an integer that when treated as a pointer points to a garbage address that might just barely be readable, but happens to contain nothing butNUL
characters, so nothing is printed.Second, assuming you wanted to see the data, not just get a count of bytes read, odds are the boot sector includes
NUL
characters early on that will cause the%s
scanning to assume the string is already done. If you want to look at the data, eitherfwrite
it to some other file for inspection, or encode it, character by character, as hex and write that tostdout
for human reading.