简体   繁体   English

在objective-c中只从磁盘读取一部分文件

[英]Read only a portion of a file from disk in objective-c

I am reading a very large file using a NSInputStream and sending them to a device in packets. 我正在使用NSInputStream读取一个非常大的文件,并将它们以数据包的形式发送到设备。 If the receiver does not get a packet, I can send back to the sender with a packet number, representing the starting location in bytes of the packet missing. 如果接收方没有收到数据包,我可以使用数据包编号发送回发送方,表示丢失数据包的起始位置(以字节为单位)。

I know an NSInputStream cannot rewind and grab the packet, but is there another way to grab the requested byte range without loading the entire large file into memory? 我知道NSInputStream无法回绕并抓取数据包,但是有没有其他方法可以获取所请求的字节范围而无需将整个大文件加载到内存中?

If there was a [NSData dataWithContentsOfFileAtPath:inRange] method, it would be perfect. 如果有[NSData dataWithContentsOfFileAtPath:inRange]方法,那将是完美的。

I don't think there's a standard function that does that, but you could write one yourself, using a category and the C stdio API: 我不认为有这样的标准函数,但您可以自己编写一个,使用类别和C stdio API:

@interface NSData(DataWithContentsOfFileAtOffsetWithSize)
+ (NSData *) dataWithContentsOfFile:(NSString *)path atOffset:(off_t)offset withSize:(size_t)bytes;
@end

@implementation NSData(DataWithContentsOfFileAtOffsetWithSize)

+ (NSData *) dataWithContentsOfFile:(NSString *)path atOffset:(off_t)offset withSize:(size_t)bytes
{
  FILE *file = fopen([path UTF8String], "rb");
  if(file == NULL)
        return nil;

  void *data = malloc(bytes);  // check for NULL!
  fseeko(file, offset, SEEK_SET);
  fread(data, 1, bytes, file);  // check return value, in case read was short!
  fclose(file);

  // NSData takes ownership and will call free(data) when it's released
  return [NSData dataWithBytesNoCopy:data length:bytes];
}

@end

Then you can this: 那么你可以这样:

// Read 100 bytes of data beginning at offset 500 from "somefile"
NSData *data = [NSData dataWithContentsOfFile:@"somefile" atOffset:500 withSize:100];

You can rewind with NSInputStream: 您可以使用NSInputStream回放:

[stream setProperty:[NSNumber numberWithInt:offset]
             forKey:NSStreamFileCurrentOffsetKey];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM