- (void)saveDataByLine{
NSString *filePath = @"/Users/xx/Library/Containers/com.ds.TMXExport/Data/Library/Caches/a.txt";
NSLog(@"filePath : %@", filePath);
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]){
// 需要创建文件,否则无法创建句柄
[[NSFileManager defaultManager] createFileAtPath:filePath contents:[@"" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}
// 如果是修改文件(会读取原来的文件内容),需要使用fileHandleForUpdatingAtPath;
// 如果使用 fileHandleForWritingAtPath,写内容到非空文件会报错
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
// NSData *read = [NSData dataWithContentsOfFile:filePath];
NSData *read = [fileHandle availableData];
NSString *text2 = [[NSString alloc] initWithData:read encoding:NSUTF8StringEncoding];
NSLog(@"avail : %@ (%lu) ", text2, (unsigned long)read.length );
for (int i = 0; i < 10; i++ ){
NSString *text = [NSString stringWithFormat:@"%d -- \n", i];
NSData *writer = [text dataUsingEncoding:NSUTF8StringEncoding];
// [writer writeToFile:filePath atomically:YES];
[fileHandle writeData:writer];
}
[fileHandle closeFile];
}
文章来源地址https://www.toymoban.com/news/detail-558006.html
文章来源:https://www.toymoban.com/news/detail-558006.html
到了这里,关于iOS/macOS - 逐行写入文件 (NSFileHandle)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!