objective-ccocoamacosdiskarbitration

Cocoa application get size of /dev/disk0s1


How could I get the size in bytes of a partition by it's device name (e.g. /dev/disk0s1) in a Cocoa application? Maybe I should use Disk Arbitration framework somehow?


Solution

  • You’re right — you can get that information by using the Disk Arbitration framework:

    DASessionRef session = DASessionCreate(NULL);
    
    if (session) {
        DADiskRef disk = DADiskCreateFromBSDName(NULL, session, "/dev/disk0s1");
    
        if (disk) {
            CFDictionaryRef diskDescription = DADiskCopyDescription(disk);
            NSDictionary *diskData = (NSDictionary *)diskDescription;
            NSString *diskSizeKey = (NSString *)kDADiskDescriptionMediaSizeKey;
            unsigned long size = [[diskData objectForKey:diskSizeKey]
                unsignedLongValue];
    
            NSLog(@"size in bytes = %lu", size);
    
            CFRelease(diskDescription);    
            CFRelease(disk);
        }
        else NSLog(@"Error while getting DA disk for /dev/disk0s1");
    
        CFRelease(session);
    }
    else NSLog(@"Error while creating DA session");
    

    Note that /dev/disk0s1 is the EFI partition.