Adding string on existing txt file -iOS

╄→гoц情女王★ 提交于 2019-12-01 10:52:27

问题


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);
}


来源:https://stackoverflow.com/questions/12682468/adding-string-on-existing-txt-file-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!