iPhone File System: Creating, Renaming and Deleting Files

Tue, Oct 27

The iPhone provides a comprehensive set of operations for working with files and directories. NSFileManager includes methods for querying the contents of directories, creating, renaming and deleting contents, as well as getting/setting file attributes (readable, writeable, etc).

Point to the Documents Directory

Each application has its own sandbox in which you can read/write files. Files written to the sandbox are persistent across invocations of the application, including across application updates.

You can locate the Documents directory in the sandbox as shown below:

// For error information
NSError *error;
 
// Create file manager
NSFileManager *fileMgr = [NSFileManager defaultManager];
 
// Point to Document directory
NSString *documentsDirectory = [NSHomeDirectory() 
         stringByAppendingPathComponent:@"Documents"];
Creating a File

With the documents directory available, we can now use that path to create a new file in the sandbox and write a few lines of text:

// File we want to create in the documents directory 
// Result is: /Documents/file1.txt
NSString *filePath = [documentsDirectory 
         stringByAppendingPathComponent:@"file1.txt"];
 
// String to write
NSString *str = @"iPhone Developer Tips\nhttp://iPhoneDevelopTips,com";
 
// Write the file
[str writeToFile:filePath atomically:YES 
         encoding:NSUTF8StringEncoding error:&error];
 
// Show contents of Documents directory
NSLog(@"Documents directory: %@",
         [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);

We build a path to the file we want to create (file1.txt), initialize a string to write into the file, and write out the contents. The last line shows a directory listing of what is in the Documents directory after we create the file, see the figure below:

Renaming a File

To rename a file we move the file to a new path. The code below creates the destination path we are after, requests to move the file, and shows the Documents directory after the move.

// Rename the file, by moving the file
NSString *filePath2 = [documentsDirectory 
                                 stringByAppendingPathComponent:@"file2.txt"];
 
// Attempt the move
if ([fileMgr moveItemAtPath:filePath toPath:filePath2 error:&error] != YES)
  NSLog(@"Unable to move file: %@", [error localizedDescription]);
 
// Show contents of Documents directory
NSLog(@"Documents directory: %@", 
         [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);

After moving the file, the output should look similar to the image below:

Deleting a File

To round out this tip, let’s look at how to delete a file:

// Attempt to delete the file at filePath2
if ([fileMgr removeItemAtPath:filePath2 error:&error] != YES)
  NSLog(@"Unable to delete file: %@", [error localizedDescription]);
 
// Show contents of Documents directory
NSLog(@"Documents directory: %@",
         [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);

Once the file is deleted, as expected, the Documents directory is now empty:

These examples touch the surface of working with files. Check out the documentation for NSFileManager for all the specifics.

9 comments

The Apple preferred (yet, abbreviated in this snippet–no check of empty array) way of getting the Documents directory is as follows:

[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0];

by Bill Heyman on Oct 27, 2009. #

Hello. Been learning Objective c for 2 weeks now. I ran this code inside an IBAction and the console only shows nothing, only that the app has started. What might I be missing.
Thanks

by Mick on Mar 6, 2011. #

If you’ve verified the code is being called inside the action method, I’m not sure where the problem could be. You could try moving the code into a place such as the app delegate to see if it works as expected.

by John Muchow on Mar 6, 2011. #

Oh Thanks, Yes I stuck that code in the AppDelegate and after I made a conection from my UIButton to the First Responder, The console showed me this:
2011-03-06 14:58:12.934 WriteToFile[7772:207] Documents directory: (
“file1.txt”
)
Now I have some reading to do, I need to understand what just happened there. This is WAY different from VB. I’m not finding many concepts that are common. Thanks for your suggestion. Mick

by Mick on Mar 6, 2011. #

I have a scenario, where I have to show 20-30++ images loaded from server, and need to store for offline, and application updates also.

Do using this kind of file writing would be helpful, rather than going with Coredata for storing images. Does this kind of storage would be helpful in handling the didReceiveMemoryWarnings..

by Pramod Jain on Jul 19, 2011. #

thanks good help

by kmarshad on Aug 16, 2011. #

Nice work! Thanks

by Suhail Larik on Sep 26, 2011. #

Nice Tips !….

by Mohsin on Sep 26, 2012. #

Rocks :)

by Yoyo on Apr 11, 2013. #