Pages

Tuesday, June 15, 2010

NSString. Write to file. Read from file.

This small program below show the simplest way to create an ASCII text file, write a string into it and read the string from the file:
#import <Foundation/Foundation.h>

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

NSString* lastLine = @"Beauty is truth, truth beauty";
NSString* fileName = @"GrecianUrn.txt";
NSString* homeDir = NSHomeDirectory();

NSString* fullPath = [homeDir stringByAppendingPathComponent:fileName];

NSError* error = nil;
[lastLine writeToFile:fullPath atomically:NO encoding:NSASCIIStringEncoding error:&error];

NSStringEncoding encoding;
NSString* contents = [NSString stringWithContentsOfFile:fullPath usedEncoding:&encoding
error:&error];

NSLog(@"Content of '%@': %@", fileName, contents);

[pool drain];
return 0;
}

No comments:

Post a Comment