gpt4 book ai didi

ios - 将 nsdata 写入文件中的特定位置

转载 作者:行者123 更新时间:2023-11-29 02:52:50 25 4
gpt4 key购买 nike

我有以下用于在文件中写入数据的代码:

NSData *chunk=...; //some data
NSArray *docDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [docDirectories objectAtIndex:0];
NSString *fileName = [docDirectory stringByAppendingPathComponent:@"TestFile.txt"];
[chunk writeToFile:fileName atomically:NO];

如果我知道文件的大小(比方说 10*chunk),并且如果我还收到文件总长度中每个 block 的位置,那么如何在该特定位置将写入数据添加到文件中?

最佳答案

要解决您的问题,最好的选择是使用 NSOutputStream ,它使此类操作更易于处理。

话虽如此,您可以像这样附加到文件末尾:

NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:filePath append:YES];
[stream open];
NSData *chunk = ...; // some data
[stream write:(uint8_t *)[chunk bytes] maxLength:[chunk length]];
[stream close];
// remember to always handle memory (if not using ARC) //

在文件中间插入一 block 数据有点复杂:

NSData *chunk = ...; // some data
NSString *filePath = ... ; // get the file //
NSUInteger insertionPoint = ...; // get the insertion point //
// make sure the file exists, if it does, do the following //
NSData *oldData = [NSData dataWithContentsOfFile:filePath];
// error checking would be nice... if (oldData) ... blah //
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:filePath append:NO];
[stream open];
[stream write:(uint8_t *)[oldData bytes] maxLength:insertionPoint]; // write the old data up to the insertion point //
[stream write:(uint8_t *)[chunk bytes] maxLength:[chunk length]]; // write the new data //
[stream write:(uint8_t *)&[oldData bytes][insertionPoint] maxLength:[oldData length] - insertionPoint]; // write the rest of old data at the end of the file //
[stream close];
// remember to always handle memory (if not using ARC) //

免责声明:在浏览器中编写的代码。

关于ios - 将 nsdata 写入文件中的特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24286780/

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