Adding string on existing txt file -iOS

2020-03-30 08:45发布

问题:

As shown code below, It is outputting several individual .txt files. However, I am looking in a way to save everything into one txt file. How could I append new string at the end of saved txt file?

-(void)saveData:(NSString *)data
{

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory=[paths objectAtIndex:0];
    NSString *fileName=[NSString stringWithFormat:@"%@/%d.txt",documentDirectory,fileInt];
    NSString *content=data;
    [content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
    NSLog(@"%@",fileName);
    fileInt++;
}

回答1:

Ok, I think I got it.

-(void)saveData:(NSString*)data
{
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentDirectory=[paths objectAtIndex:0];
        NSString *fileName=[NSString stringWithFormat:@"%@/%d.txt",documentDirectory,1];
        NSString *content=data;
        NSFileHandle *fileHandler= [NSFileHandle fileHandleForWritingAtPath:fileName];
        [fileHandler seekToEndOfFile];
        [fileHandler writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
        [fileHandler closeFile];
        NSLog(@"%@",fileName);
}