从特定位置读取特定长度的数据

时间:2014-07-17 07:12:41

标签: ios nsfilehandle

我有以下代码用于读取特定大小的文件:

  int chunksize = 1024;
  NSData*  fileData = [[NSFileManager defaultManager] contentsAtPath:URL];
  NSString* fileName = [[message.fileURL lastPathComponent] stringByDeletingPathExtension];
  NSString*  extension = [[message.fileURL pathExtension] lastPathComponent];
  NSFileHandle*  fileHandle = [NSFileHandle fileHandleForReadingAtPath:[self retrieveFilePath:fileName andExtension:extension]];
  file=@"test.png";

    int numberOfChunks =  ceilf(1.0f * [fileData length]/chunksize); //it s about 800

    for (int i=0; i<numberOfChunks; i++)
    {
        NSData *data = [fileHandle readDataOfLength:chunksize];
        ....//some code
    }

// read a chunk of 1024 bytes from position 2048
 NSData *chunkData = [fileHandle readDataOfLength:1024 fromPosition:2048];//I NEED SOMETHING LIKE THIS!!

1 个答案:

答案 0 :(得分:1)

您需要将文件指针设置为您想要读取的偏移量:

[fileHandle seekToFileOffset:2048];

然后阅读数据:

NSData *data = [fileHandle readDataOfLength:1024];

请注意,错误是以NSExceptions的形式报告的,因此您需要在大多数这些调用周围设置一些@try/@catch块。事实上,使用异常来报告错误意味着我经常使用自己的文件访问功能来简化它们的使用。例如:

+ (BOOL)seekFile:(NSFileHandle *)fileHandle
        toOffset:(uint32_t)offset
           error:(NSError **)error
{
    @try {
        [fileHandle seekToFileOffset:offset];
    } @catch(NSException *ex) {
        if (error) {
            *error = [AwzipError error:@"Failed to seek in file"
                                  code:AwzipErrorFileIO
                             exception:ex];
        }
        return NO;
    }

    return YES;
}