how to write in append mode for text file

前端 未结 3 1737
灰色年华
灰色年华 2020-11-30 06:28

My application navigation based. UItextView for notes UIViewController. I am writing data for text to file. Now i need to write in append mode , the below code i am tryin

相关标签:
3条回答
  • 2020-11-30 07:11

    Try this it works great

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *documentTXTPath = [documentsDirectory stringByAppendingPathComponent:@"Notes.txt"];
    NSString *savedString = textview.text;
    

    If file Does not exist create it and write to file or else its already created append to end of the file

    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:documentTXTPath])
    {
      [savedString writeToFile:documentTXTPath atomically:YES];
    }
    else
    {
      NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:documentTXTPath];
      [myHandle seekToEndOfFile];
      [myHandle writeData:[savedString dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    0 讨论(0)
  • 2020-11-30 07:13

    You can also do

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *documentTXTPath = [documentsDirectory stringByAppendingPathComponent:@"Notes.text"];
    NSString *content = [NSString stringWithContentsOfFile:documentTXTPath encoding:NSUTF8StringEncoding error:nil];
    content = [content stringByAppendingString:data];
    

    And again write contents to particular file path

    [content writeToFile:documentTXTPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    0 讨论(0)
  • 2020-11-30 07:17

    Remove the following line of code

    [savedString writeToFile:documentTXTPath atomically:YES];
    

    And remaining code are all fine. Anyway check my code also,

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *documentTXTPath = [documentsDirectory stringByAppendingPathComponent:@"Notes.txt"];
        NSString *savedString = textview.text;
        NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:documentTXTPath];
        [myHandle seekToEndOfFile];
        [myHandle writeData:[savedString dataUsingEncoding:NSUTF8StringEncoding]];
    
    0 讨论(0)
提交回复
热议问题