gpt4 book ai didi

objective-c - 写入文件末尾

转载 作者:行者123 更新时间:2023-12-01 17:59:47 25 4
gpt4 key购买 nike

我已经设法写入一个文本文件,但我希望能够在不覆盖文本文件当前内容的情况下向文本文件添加更多数据。所以换句话说,我想每次都写到文件的末尾,这样它就不会删除当前的内容。以下代码是我到目前为止所做的,但它每次都会覆盖并写入开头,我不知道如何让它写入结尾。基于此代码,文本文件中的当前内容如下所示:

June
July
August
September

例如,我希望能够添加以下内容
 June
July
August
September
October

有谁知道怎么做?谢谢!
-(void) writeToTextFile{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = @"June\nJuly\nAugust\nSeptember";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];

}

最佳答案

您需要 NSFileHandle

NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:fileName];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];

关于objective-c - 写入文件末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11980787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com