HFS File Types

HFS type codes are replaced by file UTIs (see Uniform Type Identifiers Overview). This article is provided for those who still need to use HFS type codes.

HFS file type and creator codes are specified by a 32-bit unsigned integer (OSType), usually represented as four characters, such as GIFf or MooV. Compilers in Mac OS X automatically convert the 4-character representation to the integer representation when they encounter four characters within single quotes, such as 'GIFf'.

OSType aFileType = 'GIFf';

You can manipulate HFS type and creator codes using NSFileManager as follows:

Other parts of Cocoa, such as NSOpenPanel, have traditionally been restricted to specifying file types by filename extension, such as "gif" or "mov". Because of the conflicting data types—strings versus integers—these filename-extension APIs cannot use HFS file types directly. These methods can instead accept HFS file types that have been properly encoded into NSString.

The Foundation Kit defines the following functions to convert between a classic HFS file type and an encoded string:

NSFileTypeForHFSTypeCode
NSHFSTypeCodeFromFileType
NSHFSTypeOfFile

The first two functions convert between an HFS file type and an encoded HFS string. The final function returns the encoded HFS string for a specific file.

As an example, when specifying the file types that can be opened by an NSOpenPanel object, you can create the array of file types as follows to include any text documents with the appropriate HFS type code:

NSArray *fileTypes = [NSArray arrayWithObjects: @"txt", @"text",
                        NSFileTypeForHFSTypeCode('TEXT'), nil];

When you need to find out whether the HFS file type or extension of a particular file is part of a set of HFS file types and extensions, you can use a function similar to this one:

BOOL FileIsValid(NSString *fullFilePath)
{
    // Create an array of strings specifying valid extensions and HFS file types.
    NSArray *fileTypes = [NSArray arrayWithObjects:
                                           @"txt",
                                           @"text",
                                           NSFileTypeForHFSTypeCode('TEXT'),
                                           nil];
 
    // Try to get the HFS file type as a string.
    NSString *fileType = NSHFSTypeOfFile(fullFilePath);
 
    if ([fileType isEqualToString:@"''"])
    {
        // No HFS type; get the extension instead.
        fileType = [fullFilePath pathExtension];
    }
 
    return [fileTypes containsObject:fileType];
}