1

我已使用此代码将字符串写入同一个文件 10 次。但它会覆盖每次新发布的先前数据。我想将新数据附加到旧数据。

[@"one" writeToFile:[self returnDocumentsDirectory] atomically:NO encoding:NSASCIIStringEncoding error:nil];


-(NSString *)returnDocumentsDirectory
{
    NSArray *DocumentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [DocumentsDirectoryPath objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:@"History.txt"];
    return filePath;
}
4

1 回答 1

2

使用以下代码写入文件

NSArray *DocumentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [DocumentsDirectoryPath objectAtIndex:0];
NSString *filePath = [path stringByAppendingPathComponent:@"History.txt"];

// Create a FileHandle
NSFileHandle *myHandle;

将以下代码放入循环中以进行多个附加操作

// Check File Exist at Location or not, if not then create new
if(![[NSFileManager defaultManager] fileExistsAtPath:filePath])
   [[NSFileManager defaultManager] createFileAtPath:filePath contents:[@"Your First String" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

// Create handle for file to update content
myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];

// move to the end of the file to add data
[myHandle seekToEndOfFile];

// Write data to file
[myHandle writeData:  [@"YOUr Second String" dataUsingEncoding:NSUTF8StringEncoding]];

// Close file
[myHandle closeFile];
于 2013-04-09T09:24:03.300 回答