Search code examples
macosnsfilemanager

Programmatically determine file content type on OSX


I am working with files whose content format has changed over multiple versions of OSX, previously it was ASCII, then JSON, now a binary plist. So I need to determine what kind of file it is so I can parse it either as text, using the JSON APIs, or loading the plist as dictionary/array.

I can use the /usr/bin/file command to tell me the file content type, but I'd prefer to do this programmatically. Is there a Cocoa API for this?

I've looked at NSFileManager attributesOfItemAtPath:error: but that just returns NSFileTypeRegular, which doesn't help.


Solution

  • There is no Cocoa API that matches file. There are a variety of different Cocoa (and CF) APIs that deal with "file types", but they use a hybrid of extensions and classic-Mac Finder info, which is not what you want.

    What you want is libmagic, as H2CO3 suggests. But you want the BSD version. It's part of the Fine Free File Command source, the same source that OS X's built-in file command comes from, and it's BSD licensed, and it's updated more frequently.

    You can get it at http://www.darwinsys.com/file/, but it's also available from Homebrew or MacPorts.