Pergunta

Estou lendo um arquivo muito grande usando um NSInputStream e enviá-los para um dispositivo em pacotes. Se o receptor não recebe um pacote, posso enviar de volta para o remetente com um número de pacotes, que representa o local a partir de bytes do pacote faltando.

Eu sei que um NSInputStream não pode rebobinar e pegar o pacote, mas existe outra maneira de agarrar o intervalo de bytes solicitado sem carregar todo o arquivo grande em memória?

Se houvesse um [NSData dataWithContentsOfFileAtPath: inRange]. Método, seria perfeito

Foi útil?

Solução

Você pode retroceder com NSInputStream:

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

Outras dicas

Eu não acho que há uma função padrão que faz isso, mas você poderia escrever um você mesmo, usando uma categoria e o 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

Em seguida, você pode esta:

// Read 100 bytes of data beginning at offset 500 from "somefile"
NSData *data = [NSData dataWithContentsOfFile:@"somefile" atOffset:500 withSize:100];
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top