打开原始磁盘并获取OS X大小

时间:2012-01-31 02:21:19

标签: c++ macos file-io disk

使用以下代码,我能够在我的机器上成功打开原始磁盘,但是当我获得磁盘长度时,我每次都得到0 ...

// Where "Path" is /dev/rdisk1 -- is rdisk1 versus disk1 the proper way to open a raw disk?
Device = open(Path, O_RDWR);
if (Device == -1)
{
    throw xException("Error opening device");
}

使用这两种方法获得大小会返回0:

struct stat st;

if (stat(Path, &st) == 0)
    _Length = st.st_size;

/

_Length = (INT64)lseek(Device, 0, SEEK_END);
        lseek(Device, 0, SEEK_SET);

我对非Windows平台上的编程并不完全熟悉,所以请原谅任何看似奇怪的东西。我的问题是:

  1. 这是在OS X下打开原始磁盘的正确方法吗?
  2. 可能导致磁盘大小返回0的原因是什么?
  3. 有问题的磁盘是未格式化的磁盘,但是对于那些想要从磁盘工具中删除信息的人(删除了非重要的东西):

    Name :  ST920217 AS Media
    Type :  Disk
    
    Partition Map Scheme :  Unformatted
    Disk Identifier      :  disk1
    Media Name           :  ST920217 AS Media
    Media Type           :  Generic
    Writable             :  Yes
    Total Capacity       :  20 GB (20,003,880,960 Bytes)
    Disk Number          :  1
    Partition Number     :  0
    

1 个答案:

答案 0 :(得分:8)

在对ioctl个请求代码进行一些搜索后,我发现了一些实际可行的内容。

#include <sys/disk.h>
#include <sys/ioctl.h>
#include <fcntl.h>

int main()
{
    // Open disk
    uint32_t dev = open("/dev/disk1", O_RDONLY);

    if (dev == -1) {
        perror("Failed to open disk");
        return -1;
    }

    uint64_t sector_count = 0;
    // Query the number of sectors on the disk
    ioctl(dev, DKIOCGETBLOCKCOUNT, &sector_count);

    uint32_t sector_size = 0;
    // Query the size of each sector
    ioctl(dev, DKIOCGETBLOCKSIZE, &sector_size);

    uint64_t disk_size = sector_count * sector_size;
    printf("%ld", disk_size);
    return 0;
}

这样的事情应该可以解决问题。我只是将我所拥有的代码复制到了那里,所以我不确定它是否可以正常编译但是它应该。