Search code examples
objective-cnslogoctal

Display an object using NSLog with octal format in objective-c


I would like to display a file's permissions in octal. The code below works but only shows the permissions in decimal. Any ideas how I can convert the result to octal? %o doesnt show the correct result.

NSString *path=@"/somepath";
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *contents = [fm contentsOfDirectoryAtPath:path error:NULL];
NSString* fullPath = nil;

for(NSString* node in contents) {

    fullPath = [NSString stringWithFormat:@"%@%@",path,node];
    NSDictionary *fileAttributes = [fm attributesOfItemAtPath:fullPath error:NULL];

    unsigned *posix=(unsigned *)[fileAttributes valueForKey:NSFilePosixPermissions];
    NSLog(@"Permissions:%@", posix); //shows 420 decimal. I need to show 644 octal

}

Thanks


Solution

  • You can use the formatting %o to output in octal. However, the fileAttributes dictionary contains NSNumber objects, so you will need to do the following for it to work:

    NSNumber *posixPermissions = [fileAttributes valueForKey:NSFilePosixPermissions];
    NSLog(@"Permissions: %o", [posixPermissions shortValue]);