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

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;


  1. launch-mailinator-com February 2, 2011 at 3:24 pm

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

    should be written as

    NSLog (@”File size is %qu bytes”,
    [attr fileSize]);

  2. Mr. Coder February 3, 2011 at 10:27 pm

    OK thanks.


Leave a Reply

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




Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.