(Windows)用C读取磁盘的引导部门

发布于 2025-02-01 16:54:55 字数 494 浏览 2 评论 0原文

我正在尝试与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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

仲春光 2025-02-08 16:54:55

首先,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 pass buf, not r, to your printf 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, which printf 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 but NUL 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, either fwrite it to some other file for inspection, or encode it, character by character, as hex and write that to stdout for human reading.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文