从磁盘读取单个扇区

时间:2009-11-18 01:35:30

标签: linux io kernel

我正在尝试直接从磁盘读取单个特定扇区。我目前已经没有想法,任何建议如何去做都会很棒!

4 个答案:

答案 0 :(得分:7)

尝试使用以下命令从CLI执行此操作:

# df -h .
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda2              27G   24G  1.6G  94% /
# dd bs=512 if=/dev/sda2 of=/tmp/sector200 skip=200 count=1
1+0 records in
1+0 records out

来自man 4 sd

FILES
   /dev/sd[a-h]: the whole device
   /dev/sd[a-h][0-8]: individual block partitions

如果您想在程序中执行此操作,只需使用来自man 2 ...的{​​{1}}和open, lseek,的系统调用,以及来自{{1的参数例子。

答案 1 :(得分:3)

我不确定最好的编程方法是什么,但是从Linux命令行可以将dd命令与磁盘的原始设备结合使用,直接从磁盘读取。

您需要sudo此命令才能访问原始磁盘设备(例如/ dev / rdisk0)。

例如,以下内容将从磁盘顶部900块的偏移量中读取一个512字节的块,并将其输出到stdout。

sudo dd if=/dev/rdisk0 bs=512 skip=900 count=1

请参阅dd手册页以获取有关dd参数的其他信息。

答案 2 :(得分:1)

在C中,它类似于以下内容......它需要root权限。我想如果你想读取单个扇区,你需要用O_DIRECT打开文件。否则你会得到一个页面。我不确定读取是否需要对齐的缓冲区,但它是用于写入的。

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define SECTOR_SIZE 512

int main(int argc, char *argv[]) {
        int offset = 0;
    int length = 5;
    int rc = -1;

    char *sector = aligned_alloc(SECTOR_SIZE, SECTOR_SIZE);
    memset(sector, 0, SECTOR_SIZE);
    /* replace XXX with the source block device */
    int fd=open("/dev/XXX", O_RDWR | O_DIRECT);

    lseek(fd, offset, SEEK_SET);
    for (int i = 0; i < length; i++) {
        rc = read(fd, sector, SECTOR_SIZE);
        if (rc < 0)
            printf("sector read error at offset = %d + %d\n %s", offset, i, strerror(errno));
        printf("Sector: %d\n", i);
        for (int j = 0; j < SECTOR_SIZE; j++) {
            printf("%x", sector[i]);
            if ((j + 1) % 16 == 0)
                printf("\n");
        }
    }
    free(sector);
    close(fd);
}

答案 3 :(得分:0)

其他人已经覆盖了它。你需要

  • 访问磁盘的设备文件(或者是root用户,或者更好,更改权限)

  • 使用文件IO函数从所述磁盘读取扇区=(通常)512字节的块。

相关问题