Search code examples
objective-cfile-permissionschmod

Objective-C: Enable/Disable File Reading (chmod a-r)


Using Objective-C, how can I give/take the permissions for all user to read a file?

I need something that has the same effects as chmod a-r and chmod a+r.

Thank you!


Solution

  • Are you also familiar with the chmod 755 file method of changing permissions? using octal numbers?

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 
    
    //Prefixing zero is octal.
    int readPermission = 04;
    int writePermission = 02;
    int executePermission = 01;
    
    //End multiplication is to shift digits left.
    int owner = (readPermission | writePermission | executePermission) * (8 * 8);   //7
    int group = (readPermission)                                       * (8);       //4 
    int other = (executePermission);                                                //1
    
    int permissions = owner + group + other;  //0741
    
    [dict setObject:[NSNumber numberWithInt:permissions] forKey:NSFilePosixPermissions]; 
    
    NSError *error = nil;
    [[NSFileManager defaultManager] setAttributes:dict ofItemAtPath:[file path] error:&error];