如何在目标 C 中执行 chmod()


C

的等价物是什么:

 chmod(MY_FILE, 0777);

在目标C中?我正在尝试写入现有的锁定文件而不执行

chmod +x MY_FILE

在终端上。

你可以使用 Cocoa 的-setAttributes:ofItemAtPath:error:来完成这项工作。

[[NSFileManager defaultManager] setAttributes:@{ NSFilePosixPermissions : @0666 }
                                 ofItemAtPath:… 
                                        error:&error];

当然,您需要这样做的权利。

你可以使用C的chmod()

在终端中输入man 2 chmod以获取文档和相关功能。

你可以使用可可来做到这一点。

NSTask *changePerms = [[NSTask alloc] init];
[changePerms setLaunchPath:@"/bin/chmod"];
NSArray *chmodArgs = [NSArray arrayWithObjects:@"666", @"/Users/abc/hello.txt", nil]; 
[changePerms setArguments:chmodArgs];
[changePerms launch];

这是使用 NSFileManager 类的另一种方式

NSDictionary* attr = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithShort:0766], NSFilePosixPermissions, NULL];
NSError *error = nil;
[[NSFileManager defaultManager] setAttributes:attr ofItemAtPath:@"/Users/abc/Desktop/test.txt" error:&error];

使用 system() 调用

system("chmod 777 /Users/abc/Desktop/test.txt");

希望这有帮助!

最新更新