目标C向文件添加内容

时间:2011-11-13 14:26:33

标签: objective-c file-io

我需要在文件中写几行。如何移动到下一行,以便每次都不会覆盖文件内容?我正在使用带有以下代码的for循环

  

[anNSString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];

NSString。在每个循环期间重新初始化anNSString。所以我需要在每个循环期间不断添加到文件路径。 感谢

3 个答案:

答案 0 :(得分:3)

我觉得接受的答案是不正确的,因为它没有回答原来的问题。要解决原始问题,您应该使用NSOutputStream,这样可以轻松地将现有内容添加到现有文件中:

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

答案 1 :(得分:1)

您只需将其全部写出来,而不是尝试逐步写入。 -[NSString writeToFile:atomically:encoding:error]每次都会覆盖该文件 - 它不会附加。

以下是插图:

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

答案 2 :(得分:0)

如果您每次都需要写一个新行,请从@ justin的答案开始,但在需要新行的地方添加[str appendString:@"\r\n"];

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

使用此代码,每个anNSString将在文本文件中的自己的行上。