WriteToFile on OSX, adding to file?

I need to write some data to a file from time to time, adding to it.

Now I have:

BOOL ok = [[NSString stringWithFormat:@"%f",raw] writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:&error]; 

How can I add new raw content to the end of a file?

+7
source share
4 answers

One method is to obtain an NSFileHandle using the fileHandleForWritingAtPath: method, converting your NSString to NSData and then calling writeData: on your NSFileHandle after moving the file pointer to the end of the file.

+6
source

Here is a method of the NSString category that will add a receiver to the specified path with the specified encoding (usually NSUTF8StringEncoding).

 - (BOOL) appendToFile:(NSString *)path encoding:(NSStringEncoding)enc; { BOOL result = YES; NSFileHandle* fh = [NSFileHandle fileHandleForWritingAtPath:path]; if ( !fh ) { [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil]; fh = [NSFileHandle fileHandleForWritingAtPath:path]; } if ( !fh ) return NO; @try { [fh seekToEndOfFile]; [fh writeData:[self dataUsingEncoding:enc]]; } @catch (NSException * e) { result = NO; } [fh closeFile]; return result; } 
+19
source

Li'l edit Peter N Lewis Answer:

 - (BOOL) appendToFile:(NSString *)path encoding:(NSStringEncoding)enc; { BOOL result = YES; NSFileHandle* fh = [NSFileHandle fileHandleForWritingAtPath:path]; if ( !fh ) { [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil]; fh = [NSFileHandle fileHandleForWritingAtPath:path]; } if ( !fh ) return NO; @try { [fh seekToEndOfFile]; [fh writeData:[strcontent dataUsingEncoding:enc]]; } @catch (NSException * e) { result = NO; } [fh closeFile]; return result; } 

Call wherever you would like

  [self appendToFile:fileName encoding:NSUTF8StringEncoding]; 
+1
source

strcontent can be self when you put this method in the Catagory of NSString.

+1
source

All Articles