Domanda

Sto leggendo un file molto grande usando un NSInputStream e inviandolo a un dispositivo in pacchetti. Se il destinatario non riceve un pacchetto, posso rispedirlo al mittente con un numero di pacchetto, che rappresenta la posizione iniziale in byte del pacchetto mancante.

So che un NSInputStream non può riavvolgere e afferrare il pacchetto, ma c'è un altro modo per afferrare l'intervallo di byte richiesto senza caricare l'intero file di grandi dimensioni in memoria?

Se esistesse un metodo [NSData dataWithContentsOfFileAtPath: inRange], sarebbe perfetto.

È stato utile?

Soluzione

Puoi riavvolgere con NSInputStream:

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

Altri suggerimenti

Non credo che ci sia una funzione standard che lo fa, ma potresti scriverne una tu stesso, usando una categoria e l'API C stdio:

@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

Quindi puoi farlo:

// Read 100 bytes of data beginning at offset 500 from "somefile"
NSData *data = [NSData dataWithContentsOfFile:@"somefile" atOffset:500 withSize:100];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top