Working with Files in Objective-C

From Techotopia
Revision as of 20:49, 10 November 2009 by Neil (Talk | contribs)

Jump to: navigation, search

In Working with Directories in Objective-C we looked at the NSFileManager, NSFileHandle and NSData Foundation Framework classes and discussed how the NSFileManager class in particular enables us to work with directories in Objective-C. In this chapter we move on from working with directories to covering the details of working with files using all three of these classes.


Contents


Creating an NSFileManager Instance

First we need to recap the steps necessary to create an instance of the NSFileManager class. As discussed in the previous chapter, the NSFileManager class contains a class method named defaultManager that is used to create an instance of the class. For example:

NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

Checking if a File Exists

The NSFileManager class contains an instance method named fileExistsAtPath that checks whether a specified file already exists. The method takes as an NSString object containing the path to file and returns a boolean YES or No value indicating the presence or otherwise of that file:

NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr fileExistsAtPath: @"/tmp/myfile.txt" ] == YES)
        NSLog (@"File exists");
else
        NSLog (@"File not found");

Comparing the Contents of Two Files

The contents of two files can be compared for equality using the contentsEqualAtPath method. This methods takes as arguments the paths to the two files to be compared and returns a boolean YES or NO to indicate whether the file contents match:

NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr contentsEqualAtPath: @"/tmp/myfile.txt" andPath: @"/tmp/sales.txt"] == YES)
        NSLog (@"File contents match");
else
        NSLog (@"File contents do not match");

Checking if a File is Readable/Writable/Executable/Deletable

Most operating systems provide some level of file access control. These typically take the form of attributes that control the level of access to a file for each user or user group. As such, it is not a certainty that your program will have read or write access to a particular file, or the appropriate permissions to delete or execute it. The quickest way to find out if your program has a particular access permission is to use the isReadableFileAtPath, isWritableFileAtPath, isExecutableFileAtPath and isDeletableFileAtPath methods. Each method takes a single argument in the form of the path to the to be checked and returns a boolean YES or NO result. For example, the following code excerpt checks to find out if a file is writable:

NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr isWritableFileAtPath: @"/tmp/myfile.txt"]  == YES)
        NSLog (@"File is writable");
else
        NSLog (@"File is read only");

To check for other access permissions simply substitute the corresponding method name in place of isWritableFileAtPath in the above example.

Moving/Renaming a File

A file may be renamed (assuming adequate permissions) using the moveItemAtPath method. This method returns a boolean YES or NO result and takes as arguments the pathname for the file to moved, the destination path and an optional NSError object into which information describing any errors encountered during the operation will be placed. If no error description information is required, this argument may be set to NULL. Note that if the destination file path already exists this operation will fail.

NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr moveItemAtPath: @"/tmp/myfile.txt" toPath: @"/tmp/newfile.txt" error: NULL]  == YES)
        NSLog (@"Move successful");
else
        NSLog (@"Move failed");

Copying a File

File copying can be achieved using the copyItemAtPath method. As with the move method, this takes as arguments the source and destination pathnames and an optional NSError object. Success of the operation is indicated by the returned boolean value:

if ([filemgr copyItemAtPath: @"/tmp/myfile.txt" toPath: @"/Users/demo/newfile.txt" error: NULL]  == YES)
        NSLog (@"Copy successful");
else
        NSLog (@"Copy failed");

Removing a File

The removeItemAtPath removes the specified file from the file system. The method takes as arguments the pathname of the file to be removed and an optional NSError object. The success of the operation is, as usual, reported in the form of a boolean YES or NO return value:

NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr removeItemAtPath: @"/tmp/myfile.txt" error: NULL]  == YES)
        NSLog (@"Remove successful");
else
        NSLog (@"Remove failed");

Creating a Symbolic Link

A symbolic to a particular file may be created using the createSymbolicLinkAtPath method. This takes arguments the path of the symbolic link, the path to the file to which the link is to refer and an optional NSError object. For example, the following code creates a symbolic link from /Users/demo/file1.txt that links to the pre-existing file /tmp/myfile.txt:

NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr createSymbolicLinkAtPath: @"/Users/demo/file1.txt" 
                withDestinationPath: @"/tmp/myfile.txt" error: NULL]  == YES)
        NSLog (@"Remove successful");
else
        NSLog (@"Remove failed");