views:

525

answers:

2

Hi

I would like to find the mount point of a volume for a given NSString path.

Though I'm a beginner in Cocoa and objective-C, I'm trying to do this "elegantly", ie. using one of the provided class, rather than making an external shell call or listing mounted filesystems and finding which one the path belongs to.

I did find NSWorkspace and getFileSystemInfoForPath, but it does not mention the mount point.

Can anybody help ?

thanks

+2  A: 

This should go something along those lines:

+ (NSString*)volumeNameForPath:(NSString *)inPath
{
    HFSUniStr255 volumeName;
    FSRef volumeFSRef;
    unsigned int volumeIndex = 1;

    while (FSGetVolumeInfo(kFSInvalidVolumeRefNum, volumeIndex++, NULL, kFSVolInfoNone, NULL, &volumeName, &volumeFSRef) == noErr) {
        NSURL *url = [(NSURL *)CFURLCreateFromFSRef(NULL, &volumeFSRef) autorelease];
        NSString *path = [url path];

        if ([inPath hasPrefix:path]) {
            return [NSString stringWithCharacters:volumeName.unicode length:volumeName.length]
        }
    }

    return nil;
}
Pierre Bernard
Failure case: Two volumes exist, “Volume with a long name” and “Volume”. The input path is “/Volumes/Volume with a long name/Some file”, and the loop gets to “/Volumes/Volume” first. Your method returns “/Volumes/Volume”, which is the wrong one.
Peter Hosey
thanks for the proposal. But I also discovered a problem with it.If I use the path /Volumes/NO NAME/some/dir/in/bootcampthe returned volume is the name of the os x partition.I was hoping there was some class/method way of finding this information, rather than resorting to string manipulation to guess the volume.
Michael C
This is untested code which I did not even try to compile. Errors and edge cases are to be expected. It derives from code I wrote for the Aperture parser in the iMedia browser. There I have the volume name stored by Aperture and need to find the full path.I guess the failure case could be resolved by making sure the path string ends with a /.
Pierre Bernard
A: 

I've run by this a month after it has been asked, but anyway: in Python standard library there's os.path.ismount() function, which detects if a path is a mount point. From its description it does it so:

The function checks whether path‘s parent, path/.., is on a different device than path, or whether path/.. and path point to the same i-node on the same device — this should detect mount points for all Unix and POSIX variants.

Mikhail Edoshin