【问题标题】:NSFileManager change file owner/permissionsNSFileManager 更改文件所有者/权限
【发布时间】:2014-08-11 04:25:29
【问题描述】:

我有一个在 root 下运行的应用程序并更改了一些由用户创建的文件。 问题是使用我的应用程序编辑文件后,它成功保存但更改了文件的所有者。 所以在编辑文件之前是:

-rw-------@ 1 myusername  wheel  2418 Jun 18 18:29 myfile.plist 

编辑后:

-rw-------@ 1 root  wheel  2418 Jun 18 18:29 myfile.plist

这是我如何编辑文件的代码:

NSMutableDictionary* myFile = [NSMutableDictionary dictionaryWithContentsOfFile:@"myFile.plist"];
[myFile setObject:@"some text" forKey:@"some key"];
BOOL result = [myFile writeToFile:@"myFile.plist" atomically:YES];

即使在 root 下使用 app 进行编辑后,我也需要保留文件的所有者。 如何解决上述问题?

编辑:我尝试了以下代码,它返回成功的结果但不更改权限:

NSDictionary *properties = [[NSFileManager defaultManager] attributesOfItemAtPath:@"myfile.plist"
                                                                            error:nil];

NSMutableDictionary *newProperties = [NSMutableDictionary dictionaryWithDictionary:properties];
[newProperties setObject:@"myusername" forKey:NSFileOwnerAccountName];

NSError *error = nil;

BOOL result = [[NSFileManager defaultManager] setAttributes:newProperties
                                               ofItemAtPath:@"myfile.plist"
                                                      error:&error];

【问题讨论】:

    标签: objective-c macos file permissions plist


    【解决方案1】:

    我相信attributesOfItemAtPath 只接受 NSNumber 对象的权限。尝试改用 AccountID:(NSFileOwnerAccountID 和/或 NSFileGroupOwnerAccountID):

    NSMutableDictionary *newProperties = [NSMutableDictionary dictionaryWithDictionary:properties];
                [newProperties setObject:[NSNumber numberWithInt:0] forKey:NSFileOwnerAccountID];
    

    来自 Apples 文档:

    NSFilePosixPermissions 值必须初始化为 代表 POSIX 文件权限位模式的代码,其中 对应的值是一个 NSNumber 对象。

    参考:NSFileOwnerAccountID

    【讨论】:

      【解决方案2】:

      你可以使用NSFileManager的setAttributes:ofItemAtPath:error:方法和NSFileImmutable的属性:

      NSDictionary* attribs = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:NSFileImmutable];
      [[NSFileManager defaultManager]  setAttributes: attribs ofItemAtPath:@"/path/to/file" error:nil];
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2016-02-04
        • 2012-04-03
        • 2011-04-13
        • 1970-01-01
        • 2011-12-16
        • 1970-01-01
        • 1970-01-01
        • 2018-05-29
        • 2016-11-27
        相关资源
        最近更新 更多