在Objective-c中,有效的方法将数据从二进制文件直接读入uint8_t数组?

时间:2017-02-23 14:43:56

标签: objective-c arrays

我有一个大的一维uint8_t数组,我无法找到一种有效的方法来填充二进制文件中的数据,而无需先将数据导入为NSData。是否有更有效的方法来填充我的uint8_t数组而不首先作为NSData导入?

我在另一篇关于(WRITE uint8_t array directly to binary file)的回复帖子中以迂回的方式提出这个问题,但我不确定答案是否相同。你可以看到我在那里编写阅读的尝试。

谢谢,戴尔

编辑:对不起,实际上我想要同步/阻塞,但我发现如何使用NSInputStream,所以我做了一个粗略的测试代码功能。代码运行并在最后留下内存使用量(少于约4096个ARC应该处理),因为它开始时所以我觉得我现在很开心:)除非有人看到我的实现有问题吗?

答案的测试代码:

- (void) read_file
{
  NSInteger thisRead;
  uint8_t inbuffer[4096];
  uint32_t pos = 0;
  uint8_t haderr = 0;
  double strt= CACurrentMediaTime();
  NSInputStream *iStream = [[NSInputStream alloc] initWithFileAtPath:dataPath];
  [iStream open];
  while ((thisRead = [iStream read:inbuffer maxLength:4096]) != 0){
     if (thisRead>0){
        memcpy(ONOFFrecords+pos, inbuffer, thisRead);
        pos+=thisRead;
     }else{
        haderr=1;
        NSLog(@"Error %@",[iStream streamError]);
        break;
     }
  }
  [iStream close];
  if (haderr==0){
     NSLog(@"8 MB file of uint8_t's READ in %f secs with first uint8_t = %u last pos %u", CACurrentMediaTime()-strt,ONOFFrecords[0],pos);
  }
}

0 个答案:

没有答案