0

我需要将单独的行放入文件中,但似乎不受支持

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    // the path to write file
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"myFile"];

    [dataString writeToFile:appFile atomically:YES];

它确实将一个字符串放入文件中,但它会覆盖前一个。

有什么建议么?

4

2 回答 2

2

要将数据附加到现有文件,NSFileHandle请为该文件创建一个实例,然后调用-seekToEndOfFileand finally -writeData:。您必须自己将字符串转换为NSData对象(使用正确的编码)。完成后不要忘记关闭文件句柄。

更简单但效率较低的方法是将现有文件内容读入字符串,然后将新文本附加到该字符串并将所有内容再次写入磁盘。不过,我不会在执行 2000 次的循环中这样做。

于 2011-03-22T13:48:17.747 回答
0

谢谢奥莱!这就是我一直在寻找的。

其他一些示例代码:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//creating a path
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"nameOfAFile"];
//clearing or creating (NSFileHande doesn't support creating a file it seems)
NSString *nothing = @""; //remember it's CLEARING! so get rid of it - if you want keep data
[nothing writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:nil];

//creating NSFileHandle and seeking for the end of file
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:appFile];
[fh seekToEndOfFile];

//appending data do the end of file
NSString *dataString = @"All the stuff you want to add to the end of file";        
NSData *data = [dataString dataUsingEncoding:NSASCIIStringEncoding];
[fh writeData:data];

//memory and leaks
[fh closeFile];
[fh release];
[dataString release];
于 2011-03-23T11:14:30.783 回答