繁体   English   中英

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

[英]Open Raw Disk and Get Size OS X

使用以下代码,我能够成功打开计算机上的原始磁盘,但是当我获得磁盘长度时,每次都会得到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?

有问题的磁盘是未格式化的磁盘,但对于那些希望从“磁盘工具”中获取信息的用户(已删除了不重要的内容):

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

在搜索完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;
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM