How to convert a classic HFS path into a POSIX path

后端 未结 2 1182
北海茫月
北海茫月 2020-12-22 05:55

I am reading old files that still use HFS style paths, such as VolumeName:Folder:File.

I need to convert them into POSIX paths.

I do not like to

2条回答
  •  误落风尘
    2020-12-22 06:31

    A solution in Obj-C and Swift as category / extension of NSString / String. The unavailable kCFURLHFSPathStyle style is circumvented in the same way as in the linked question.

    Objective-C

    @implementation NSString (POSIX_HFS)
    
        - (NSString *)POSIXPathFromHFSPath
        {
            NSString *posixPath = nil;
            CFURLRef fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)self, 1, [self hasSuffix:@":"]); // kCFURLHFSPathStyle
            if (fileURL)    {
                posixPath = [(__bridge NSURL*)fileURL path];
                CFRelease(fileURL);
            }
    
            return posixPath;
        }
    
    @end
    

    Swift

    extension String {
    
        func posixPathFromHFSPath() -> String?
        {
            guard let fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
                                                              self as CFString?,
                                                              CFURLPathStyle(rawValue:1)!,
                                                              self.hasSuffix(":")) else { return nil }
            return (fileURL as URL).path
        }
    }
    

提交回复
热议问题