Reputation: 3155
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!
Upvotes: 1
Views: 1427
Reputation: 32066
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];
Upvotes: 6
Reputation: 365697
To do this in Objective C:
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
NSDict *attribs = [fm attributesOfItemAtPath:[file path] error:&error];
int permissions = [[attribs objectForKey:@"NSFilePosixPermissions"] intValue];
permissions |= (S_IRSUR | S_IRGRP | S_IROTH);
NSDict *newattribs = [NSDict dictionaryWithObject:[NSNumber numberWithInt:permissions]
forKey:NSFilePosixPermissions];
[fm setAttributes:dict ofItemAtPath:[file path] error:&error];
Or, just get a POSIX path (with -[NSFileManager fileSystemRepresentationForPath]) and do it in C, using the chmod function—which is what the chmod command-line tool uses, and is portable to any POSIX platform.
Upvotes: 3