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

Lan*_*der 10 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");
}
Run Code Online (Sandbox Code Playgroud)

使用这两种方法获取大小将返回0:

struct stat st;

if (stat(Path, &st) == 0)
    _Length = st.st_size;
Run Code Online (Sandbox Code Playgroud)

/

_Length = (INT64)lseek(Device, 0, SEEK_END);
        lseek(Device, 0, SEEK_SET);
Run Code Online (Sandbox Code Playgroud)

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

  1. 这是在OS X下打开原始磁盘的正确方法吗?
  2. 可能导致磁盘大小返回为0的原因是什么?

有问题的磁盘是一个未格式化的磁盘,但对于那些想要从磁盘工具中获取信息的人(删除了非重要的东西):

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
Run Code Online (Sandbox Code Playgroud)

Lan*_*der 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;
}
Run Code Online (Sandbox Code Playgroud)

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