如何以附加模式写入文本文件
我的应用程序基于导航。 UItextView 用于注释 UIViewController。我正在将文本数据写入文件。现在我需要在附加模式下编写,我正在尝试以下代码,但每次都使用相同的文本数据写入两次,并且不附加下一个文本数据到文件。
- (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];
}
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];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
删除下面这行代码
,剩下的代码就都没有问题了。无论如何也检查我的代码,
Remove the following line of code
And remaining code are all fine. Anyway check my code also,
尝试一下它效果很好
如果文件不存在创建它并写入文件,否则它已经创建附加到文件末尾
Try this it works great
If file Does not exist create it and write to file or else its already created append to end of the file
您还可以
再次将内容写入特定文件路径
You can also do
And again write contents to particular file path