Working with files in Objective C

By | December 22, 2010

Basic file operations
Assumes the existence of a file called “testfile”
in the current working directory

#import 
#import 
#import 
#import 
#import 
int main (int argc, char *argv[])
{
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	NSString *fName = @”testfile”;
	NSFileManager *fm;
	NSDictionary *attr;
	// Need to create an instance of the file manager
	fm = [NSFileManager defaultManager];
	// Let’s make sure our test file exists first
	if ([fm fileExistsAtPath: fName] == NO)
	{
		NSLog (@”File doesn’t exist!”);
		return 1;
	}
// Now let’s make a copy

	if ([fm copyPath: fName toPath: @”newfile” handler: nil] == NO)
	{
		NSLog (@”File copy failed!”);
		return 2;
	}
	// Let’s test to see if the two files are identical
	if ([fm contentsEqualAtPath: fName andPath: @”newfile”] == NO)
	{
		NSLog (@”Files are not equal!”);
		return 3;
	}
	// Now let’s rename the copy
	if ([fm movePath: @”newfile” toPath: @”newfile2” handler: nil] == NO)
	{
		NSLog (@”File rename failed!”);
		return 4;
	}
	// Get the size of newfile2
	if ((attr = [fm fileAttributesAtPath: @”newfile2” traverseLink: NO]) == nil)
	{
		NSLog (@”Couldn’t get file attributes!”);
		return 5;
	}
	NSLog (@”File size is %i bytes”,[[attr objectForKey: NSFileSize] intValue]);
	// And finally, let’s delete the original file
	if ([fm removeFileAtPath: fName handler: nil] == NO)
	{
		NSLog (@”File removal failed!”);
		return 6;
	}
	NSLog (@”All operations were successful!”);
	// Display the contents of the newly-created file
	NSLog(@”%@” [NSString stringWithContentsOfFile: @”newfile2”]);
	[pool drain];
	return 0;
}

2 thoughts on “Working with files in Objective C

Leave a Reply

Your email address will not be published. Required fields are marked *