Pages

Sunday, January 3, 2010

Objective-C. Basic File Operations

#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>
#import <Foundation/NSFileManager.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSDictionary.h>

int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSFileManager *fm;
NSString *fName = @"testfile";
NSDictionary *attr;

fm = [NSFileManager defaultManager];

if ([fm fileExistsAtPath: fName] == NO)
{
NSLog(@"File does not exist!");
return 1;
}

if ([fm copyPath:fName toPath:@"newFile" handler: nil] == NO)
{
NSLog(@"File copy failed");
return 2;
}

if ([fm movePath: @"newFile" toPath: @"newFile2" handler: nil] == NO)
{
NSLog(@"File rename failed");
return 3;
}

attr = [fm fileAttributesAtPath: @"newFile2" traverseLink: NO];
if (attr == nil)
{
NSLog(@"Couldn't get file attribute");
return 4;
}

NSLog(@"File size is %i bytes", [[attr objectForKey: NSFileSize]
intValue]);

if ([fm removeFileAtPath: fName handler: nil] == NO)
{
NSLog(@"File removal failed");
return 5;
}

NSLog(@"All operations were successfull");

NSLog(@"%@", [NSString stringWithContentsOfFile: @"newFile2"
encoding: NSUTF8StringEncoding
error: nil]);
[pool drain];
return 0;
}
Foundation framework allow to perform a set of basic file operations such as create, rename, move, copy, delete a file. The program above demonstrates NSFileManager class in action.

The program uses testfile - a text file. You can create it in Xcode by selecting New File.. from the File menu. In the left pane that appears, highlight Other, and select Empty file in the right pane. The file should be in Build\Debug folder.

Foundation framework provides a special class NSData (and, of course NSMutableData) that is used as a temporary buffer for file read/write operations. It is used together with the NSFileManager as it is shown below:
#import <Foundation/NSObject.h>
#import <Foundation/NSFileManager.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSData.h>

int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSFileManager *fm;
NSData *fileData;

fm = [NSFileManager defaultManager];
fileData = [fm contentsAtPath: @"testFile"];

if (fileData == nil)
{
NSLog(@"File read failed");
return 1;
}

BOOL bCreated = [fm createFileAtPath: @"newFile" contents: fileData attributes: nil];
if (bCreated == YES)
NSLog(@"File newFile created.");

[pool drain];
return 0;
}

No comments:

Post a Comment