0

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.

brianpartridge
  • 763
  • 8
  • 19

2 Answers2

2

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.

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • Thanks for this, this looks much more promising than the source forge link. I was hoping to avoid a dependency, but this should suffice. Thanks. – brianpartridge Jun 08 '12 at 23:57
0

This might help you: http://sourceforge.net/projects/libmagic/ Here's a man page for Libmagic on Linux; as this is not quite an OS-dependent library, this is very likely to work without modification for Mac also. See http://linux.die.net/man/3/libmagic

  • Unfortunately, the project appears abandoned and untouched since 2000. The GPL license makes me balk too as I this may be part of a product some day. I was hoping for a Cocoa method that would just utilize the same code as the 'file' command. – brianpartridge Jun 08 '12 at 18:32
  • 1
    @brianpartridge: Where do you get "abandoned and untouched since 2000" from a page that says "Last Update 2009-07-17"? – abarnert Jun 08 '12 at 21:18
  • @H2CO3: While you can get a file command that uses the library you just provided, that's not the one that comes with OS X--or any other *nix that I know of, including linux distros. – abarnert Jun 08 '12 at 21:20
  • @abarneert I didn't see anything about 2009, but oh well the new link you posted looks promising. – brianpartridge Jun 08 '12 at 23:55