AP.
AP.

Reputation: 5323

Get the file type in Mac OS

I am trying to get the type of file (the one show in Finder in list view) for a given file. Is there a simple way to achieve this?

Upvotes: 3

Views: 405

Answers (1)

Sherm Pendley
Sherm Pendley

Reputation: 13612

Have a look at NSWorkspace's -typeOfFile:error: and -localizedDescriptionForType: methods. Here's a quick example of a command-line tool that will print the info for the files you specify as arguments when you run it:

#import <Cocoa/Cocoa.h>

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    if (argc > 1) {
        for(int i = 1; i < argc; ++i) {
            NSString *theFile = [NSString stringWithFormat:@"%s", argv[i]];
            NSWorkspace *ws = [NSWorkspace sharedWorkspace];
            NSString *fileType = [ws typeOfFile:theFile error:nil];
            NSString *fileDesc = [ws localizedDescriptionForType:fileType];
            NSLog(@"File:%@ Type:%@ Description:%@", theFile, fileType, fileDesc);
        }
    }

    [pool drain];
    return 0;
}

Note that Xcode's default "command line tool" project only links to Foundation - you'll need to change its #include to Cocoa, and add Cocoa.framework if you want to build the above example. You probably won't need to build it though - it's simple enough that you can probably get the info you need without doing that.

Upvotes: 4

Related Questions