jpo
jpo

Reputation: 4059

Objective C Adding content to a file

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

Upvotes: 3

Views: 1464

Answers (3)

Dario
Dario

Reputation: 671

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];

Upvotes: 3

GeneralMike
GeneralMike

Reputation: 3001

If you need to write to a new line each time, start with what is in @justin's answer, but add [str appendString:@"\r\n"]; wherever you need new lines.

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];
    [str appendString:@"\r\n"]; //****** THIS IS THE NEW LINE ******
}

NSError * outError(0);
BOOL success = [str writeToFile:path
                     atomically:YES
                       encoding:NSUTF8StringEncoding
                          error:&outError];
[str release];
...

With this code, each anNSString will be on it's own line in the text file.

Upvotes: 0

justin
justin

Reputation: 104728

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];
...

Upvotes: 1

Related Questions