35: Examples of reading and writing plain text files in Cocoa using C and Objective-C

Problem: we want to read and write plain text files without the overhead of creating a document based Cocoa application.


Three sets of examples:

  • A C based approach using fopen, fclose, fprintf and fscanf for when the names of the files are known.

  • Ditto using NSString methods stringByAppendingFormat, stringWithContentsOfFile and componentsSeparatedByString together with NSScanner.

  • Use NSOpenPanel and NSSavePanel to specify the filenames then use one of the preceding to read and write.


C based approach

- (void)writeUsingC { FILE *fp = fopen("../../../fred.txt","w"); NSInteger i; for(i = 0;i < 5; i++){ fprintf(fp,"i=%d\n",(int)i); } fclose(fp); } - (void)readUsingC { FILE *fp = fopen("../../../fred.txt","r"); int k; char myStr[20]; NSInteger i; for(i = 0;i < 5; i++){ fscanf(fp,"%s %d\n",myStr,&k); NSLog(@"i=%d,%s k=%d",i,myStr,k); } fclose(fp); }


Objective-C using NSString and NSScanner

- (void)writeUsingObjectiveC { NSString * zStr = [[NSString alloc]init]; NSInteger i; for (i = 0; i < 5; i++) { zStr = [zStr stringByAppendingFormat:@"i=%d\n",i]; } [zStr writeToFile:@"../../../barney.txt" atomically:YES encoding:NSASCIIStringEncoding error:NULL]; } - (void)readUsingObjectiveC { NSString * zStr = [NSString stringWithContentsOfFile:@"../../../barney.txt" encoding:NSASCIIStringEncoding error:NULL]; // extract the data line by line NSArray * zAryOfLines = [zStr componentsSeparatedByString:@"\n"]; if([zAryOfLines count] == 0) { NSLog(@"zAryOfLines count = 0"); return; } for (NSString * zStrLine in zAryOfLines) { NSInteger zInt; NSString * zStr2; NSScanner* zScanner = [NSScanner scannerWithString:zStrLine]; [zScanner scanString:@"i=" intoString:&zStr2]; [zScanner scanInteger:&zInt]; NSLog(@"zStr2="%@", zInt=%d",zStr2,zInt); } }


Use NSOpenPanel and NSSavePanel

- (void)writeUsingSavePanel { // create the string to be written NSString * zStr = [[NSString alloc]init]; NSInteger i; for (i = 0; i < 5; i++) { zStr = [zStr stringByAppendingFormat:@"i=%d\n",i]; } // get the file url NSSavePanel * zSavePanel = [NSSavePanel savePanel]; NSInteger zResult = [zSavePanel runModal]; if (zResult == NSFileHandlingPanelCancelButton) { NSLog(@"writeUsingSavePanel cancelled"); return; } NSURL *zUrl = [zSavePanel URL]; //write BOOL zBoolResult = [zStr writeToURL:zUrl atomically:YES encoding:NSASCIIStringEncoding error:NULL]; if (! zBoolResult) { NSLog(@"writeUsingSavePanel failed"); } } - (void)readUsingOpenPanel { // get the url of a .txt file NSOpenPanel * zOpenPanel = [NSOpenPanel openPanel]; NSArray * zAryOfExtensions = [NSArray arrayWithObject:@"txt"]; [zOpenPanel setAllowedFileTypes:zAryOfExtensions]; NSInteger zIntResult = [zOpenPanel runModal]; if (zIntResult == NSFileHandlingPanelCancelButton) { NSLog(@"readUsingOpenPanel cancelled"); return; } NSURL *zUrl = [zOpenPanel URL]; // read the file NSString * zStr = [NSString stringWithContentsOfURL:zUrl encoding:NSASCIIStringEncoding error:NULL]; NSLog(@"zStr=\n%@",zStr); }

If you want to download the code

Click the Download Link to obtain 035-Read-Write.zip file of this OS X 10.6 Snow Leopard program.

Download 035-Read-Write.zip (2.4 MB)



Please send me your comments

If you include your e-mail I may reply!  

Page last modified: 18:58 Sunday 12th. May 2013

Julius Guzy

Paintings & Drawings

  • Link to drawing made from painting by Rubens of the Feast of Venus

animatedPaint