File Handling in Objective-c


File handling cannot be explained visually with the application and hence the key methods that are used for handling files are explained below. Please note that the application bundle only has read permission and we wont be able to modify the files. We can anyway modify documents directory of your application.

Methods used in File Handling

The list of the methods used for accessing and manipulating files are listed below. Here we have to replace the FilePath1, FilePath2 and FilePath strings to our required full file paths to get the desired action.

Check if file exists at a path

   NSFileManager *fileManager = [NSFileManager defaultManager];
   //Get documents directory
   NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
   (NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
   if ([fileManager fileExistsAtPath:@""]==YES) {
        NSLog(@"File exists");

Comparing two file contents

   if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) {
      NSLog(@"Same content");

Check if writable, readable and executable

   if ([fileManager isWritableFileAtPath:@"FilePath"]) {
   if ([fileManager isReadableFileAtPath:@"FilePath"]) {
   if ( [fileManager isExecutableFileAtPath:@"FilePath"]){
      NSLog(@"is Executable");

Move file

   if([fileManager moveItemAtPath:@"FilePath1" 
   toPath:@"FilePath2" error:NULL]){
      NSLog(@"Moved successfully");

Copy file

   if ([fileManager copyItemAtPath:@"FilePath1" 
   toPath:@"FilePath2"  error:NULL]) {
      NSLog(@"Copied successfully");

Remove file

   if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
      NSLog(@"Removed successfully");

Read file

   NSData *data = [fileManager contentsAtPath:@"Path"];

Write file

   [fileManager createFileAtPath:@"" contents:data attributes:nil];



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at

Up ↑

%d bloggers like this: