I need to write several line to a file. How can I move to the next line so that the file content is not overwritten each time? I am using a for loop with the following code in it
[anNSString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
The NSString. anNSString is reinitialized during each loop. SO i need to keep adding to the file path each during each loop. Thanks
I feel like the accepted answer is not correct since it didn't answer the original question. To solve the original question you should use an NSOutputStream it makes appending content to an existing file an easy task:
NSString *myString = @"Text to append!"; // don't forget to add linebreaks if needed (\r\n)
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:filePath append:YES];
[stream open];
NSData *strData = [myString dataUsingEncoding:NSUTF8StringEncoding];
[stream write:(uint8_t *)[strData bytes] maxLength:[strData length]];
[stream close];
You just write it out all at once, rather than attempting to write it incrementally. -[NSString writeToFile:atomically:encoding:error] will just overwrite the file each time - it does not append.
Here's an illustration:
NSMutableString * str = [NSMutableString new];
// > anNSString is reinitialized during each loop.
for ( expr ) {
NSString * anNSString = ...;
// > SO i need to keep adding to the file path each during each loop.
[str appendString:anNSString];
}
NSError * outError(0);
BOOL success = [str writeToFile:path
atomically:YES
encoding:NSUTF8StringEncoding
error:&outError];
[str release];
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With