In this application ,we will learn how to retrieve and set specific file/directory attributes. We have been specifying nil for the dictionary attributes of files and directories, specifiy a dictionary which provides attributes that are different from the default.We can alter the attributes of a file system object after it has been created.
Step 1: We give an example showing how you can retrieve /set the attributes of a file. We simply define in the main() function of the program.
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp/file.txt"];
NSData *data = [@"Hello! This is a line " dataUsingEncoding:NSUTF8StringEncoding];
success = [fileManager createFileAtPath:filePath contents:data attributes:nil];
if(success == NO) {
NSLog(@"Error creating file");
return -1;
}
NSDictionary *attributes = [fileManager fileAttributesAtPath:filePath traverseLink:NO];
if(attributes){
NSNumber *fSize = [attributes objectForKey:NSFileSize];
NSLog(@"File Size is %qi",[fSize longLongValue]);
}
NSDictionary *newAttributes;
NSError *error;
newAttributes = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
forKey:NSFileExtensionHidden];
success = [fileManager setAttributes:newAttributes
ofItemAtPath:filePath error:&error];
if(success == NO){
NSLog (@"Error setting attributes of file. Error :%@", [error localizedDescription]);
return -1;
}
attributes = [fileManager fileAttributesAtPath: filePath traverseLink :NO];
[pool release];
return 0;
}
Step 2: It starts by creating file.txt file in tmp with a one line text store in it. We first obtain an NSData object from a string by using the NSString’s instance method dataUsingEnc0ding: with utf-8 encoding. We create the file using createFileAtPath:contents:attributes: method.
Step 3: After creating the file using default attributes. To retrieve the file’s attributes of a file, we use the NSFileManager’s instant method fileAttributesAtPath:traverseLink: which we declared already in the code.
Step 4: If compile and run the application , then we’ll see the output in the Debugger console.











