如何在文本文件的追加模式下编写 [英] how to write in append mode for text file

查看:151
本文介绍了如何在文本文件的追加模式下编写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序导航基础。 UItextView用于备注UIViewController。我正在写文本数据到文件。现在我需要写下附加模式,下面的代码我正在尝试,但每次用相同的文本数据写入两次,并且如果下一个文本数据到文件则不附加。

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 trying but every time is writing to two time with same text data, and not appending if next text data to file.

- (void)saveText:(id)sender
{
    [self.textview resignFirstResponder];
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [documentPaths objectAtIndex:0];
    NSString *documentTXTPath = [documentsDirectory stringByAppendingPathComponent:@"Notes.txt"];
    NSString *savedString = textview.text;
    [savedString writeToFile:documentTXTPath atomically:YES];


    NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:documentTXTPath ];
    [myHandle seekToEndOfFile];
    [myHandle writeData:  [savedString dataUsingEncoding:NSUTF8StringEncoding]];
    [myHandle closeFile];

}


推荐答案

删除下面一行代码

[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]];

这篇关于如何在文本文件的追加模式下编写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆