我正在尝试构建自己的C程序,它基本上就像fdisk vdisk'p'命令一样工作。我只想读取磁盘的前512个字节,lseek到(0x1BE)分区的开头,然后读取分区类型,名称,大小等。我不确定如何实际读取这些值。我使用read()linux函数读取512个字节,但是当我尝试以任何方式显示/查看它们时,没有显示任何内容。我做错了什么?
int main(int argc, char *argv[]) {
int bytes_read;
char mbr[512];
int file;
if(argc == 1) {
// Print some help info
printf ("Here is some help info: \n\n");
} else if(argc < 3) {
printf("File: %s\n\n", argv[1]);
file = open(argv[1], O_RDONLY);
lseek(bytes_read, 0, 0);
//First get the MBR
bytes_read = read(file, mbr, 512);
printf("MBR=%s\n\nbytes_read=%d\n\n", mbr, bytes_read);
} else {
printf ("Incorrect usage: fdisk <disk>\n\n");
}
}
答案 0 :(得分:3)
不要尝试将printf
与二进制数据一起使用。如果您的二进制数据以NUL
(ASCII 0)开头,则printf将假定您有一个空字符串。您可以使用write()
写出任意数据(需要缓冲区和长度),例如:
#include <unistd.h>
write(STDOUT_FILENO, mbr, 512)
...但即使这样也不一定显示任何有用的东西,因为您的终端可能会尝试解释输出中的控制字符。你最好的办法就是将输出管道输出到xxd
或od
之类,这两个输出都会产生输入数据的十六进制。
例如,我本地驱动器的前512个字节都是NUL
。在代码中使用write()
(并删除lseek
)会在输出中产生512 NUL
个字节。尝试将除磁盘之外的其他内容传递给您的代码,例如:
myexe /etc/passwd
标准DOS MBR的结构记录为here,表明您可能从这样的数据结构开始:
struct _partition {
uint8_t status;
uint8_t chs_start[3];
uint8_t part_type;
uint8_t chs_end[3];
uint32_t lba_start;
uint32_t sectors;
};
并填充这样的内容:
fd = open(target, O_RDONLY);
lseek(fd, 446, SEEK_SET);
for (i=0; i<4; i++) {
struct _partition p;
bytes_read = read(fd, &p, sizeof(struct _partition));
// assume this prints information to stdout or something.
print_part(i, &p);
}
答案 1 :(得分:0)
摆脱lseek
。你的编译器现在应该抛出一个警告,因为你传递了一个尚未初始化的参数(bytes_read
)。
完成后,您需要做一些事情来显示内容;现在,你没有任何东西可以使用你读过的数据。