1

使用 Objective-C,我如何授予/获取所有用户读取文件的权限?

我需要与 和 具有相同效果的chmod a-r东西chmod a+r

谢谢!

4

2 回答 2

6

您是否也熟悉chmod 755 file更改权限的方法?使用八进制数?

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];
于 2012-06-13T19:24:48.350 回答
3

要在目标 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];

或者,只需获取一个 POSIX 路径(使用 -[NSFileManager fileSystemRepresentationForPath])并在 C 中使用 chmod 函数执行此操作 - 这是 chmod 命令行工具使用的,并且可以移植到任何 POSIX 平台。

于 2012-06-13T20:27:48.843 回答