简体   繁体   中英

NSFileManager change file owner/permissions

I have an application which running under root and changes some file which was created by user. The problem is that after editing file using my application it saves succesfully but changes owner of file. So before editing file was:

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

After editing:

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

Here is a code how I edit a file:

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

I need to keep file's owner even after editing using app under root. How can I solve the problem above?

EDIT: I tried the following code and it return successful result but doesn't change permissions:

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];

I believe for permissions only NSNumber objects are accepted for attributesOfItemAtPath . Try using AccountID instead: ( NSFileOwnerAccountID and/or NSFileGroupOwnerAccountID ):

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

From Apples Documentation :

NSFilePosixPermissions value must be initialized with the code representing the POSIX file-permissions bit pattern, in which the corresponding value is an NSNumber object.

Reference: NSFileOwnerAccountID

You can use the setAttributes:ofItemAtPath:error: method of NSFileManager with an attribute of NSFileImmutable :

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

Hope this helps !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM