【问题标题】:write nsdata in a file at a specific position将 nsdata 写入文件的特定位置
【发布时间】:2014-06-18 13:24:36
【问题描述】:

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

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),并且如果我还收到每个块在文件总长度中的位置,我如何在该特定位置将写入数据添加到文件?

【问题讨论】:

  • 要写在文件末尾吗?如果不是,是否要插入新数据并将插入点之后的数据移动到文件末尾?或者,您想用新数据替换插入点的数据吗?
  • 我要插入新数据,并将数据移到插入点之后。我也可能遇到必须在文件末尾添加数据的 cae。所以这两种情况都可能发生

标签: ios file-io nsdata writetofile


【解决方案1】:

要解决您的问题,最好的办法是使用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) //

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

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) //

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

【讨论】:

  • NSOutputStream 比 NSFileHandle 有什么优势?
  • 这里唯一真正的优势是能够指定每个操作写入多少数据,而不是NSFileHandle 将整个NSData 对象写入文件。如果您要对文件执行的唯一操作是写入操作,我相信NSOutputStream 是更直接的解决方案;但是NSFileHandle 显然是灵活性的赢家,如果您想执行更复杂的操作。
  • 谢谢!创建文件时文件的长度是否重要?
  • 插入点是插入点吗?在 [stream close] 上方的最后一行,我收到一条错误消息: Operand of type çonst void'where 需要算术或指针类型
  • 是的,抱歉打错了,我编辑了答案,将变量从 insertPoint 重命名为 insertionPoint 并添加了 & 以从数据数组中获取正确的地址。
猜你喜欢
  • 1970-01-01
  • 2013-12-06
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
相关资源
最近更新 更多