Thursday, May 9, 2013

NSDictionary filePosixPermissions example ios


Returns the value for the key NSFilePosixPermissions.
- (NSUInteger)filePosixPermissions
Return Value
The value, as an unsigned long, for the key NSFilePosixPermissions, or 0 if the dictionary doesn’t have an entry for the key.
Discussion of [NSDictionary filePosixPermissions]
This and the other file... methods are for use with a dictionary, such as those returned from the methodsfileAttributesAtPath:traverseLink: (NSFileManager), directoryAttributes(NSDirectoryEnumerator), and fileAttributes (NSDirectoryEnumerator), that represents the POSIX attributes of a file or directory. This method returns the file’s permissions.
Example of [NSDictionary filePosixPermissions]
// The indices of the items in the permsArray correspond to the POSIX
// permissions. Essentially each bit of the POSIX permissions represents
// a read, write, or execute bit.
NSArray *permsArray = [NSArray arrayWithObjects:@"---", @"--x", @"-w-", @"-wx", @"r--", @"r-x", @"rw-", @"rwx", nil];
NSFileManager *fm = [[[NSFileManager alloc] init] autorelease];
NSMutableString *result = [NSMutableString string];
NSDictionary *attrs = [fm attributesOfItemAtPath:@"some/path.txt" error:NULL];

if (!attrs)
    return nil;

NSUInteger perms = [attrs filePosixPermissions];

if ([[attrs fileType] isEqualToString:NSFileTypeDirectory])
    [result appendString:@"d"];
    [result appendString:@"-"];

// loop through POSIX permissions, starting at user, then group, then other.
for (int i = 2; i >= 0; i--)
    // this creates an index from 0 to 7
    unsigned long thisPart = (perms >> (i * 3)) & 0x7;

    // we look up this index in our permissions array and append it.
    [result appendString:[permsArray objectAtIndex:thisPart]];

return result;
Example of [NSDictionary filePosixPermissions]
NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:  @"Documents"];
NSFileManager *localFileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *dirEnum =
    [localFileManager enumeratorAtPath:docsDir];

NSString *file;
while (file = [dirEnum nextObject]) {
            if ( [file isEqualToString: _The_NAME_YOU_ARE_LOOKING_FOR_] ) {
            NSString *fullPath = [NSString stringWithFormat:@"%@/%@", docsDir,file];
                // READ YOUR FILE FROM HERE
            NSDictionary *attrs = [localFileManager 
                       attributesOfItemAtPath:fullPath error:&error];
            if ( error ) {
               NSLog(@" error - %@", error);
            } else {
                NSLog(@" file : %@", file);
                NSInteger fsiz = [attrs fileSize];
                NSString *ftyp = [attrs fileType];
                NSDate   *fmod = [attrs fileModificationDate];
                            NSInteger fperm= [attrs filePosixPermissions];
                NSLog(@"  %9d : %@ : %@ : %@ : %d",  fsiz, file, ftyp, fmod, fperm );