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

Ios 从特定位置读取特定长度的数据,ios,nsfilehandle,Ios,Nsfilehandle,我有以下代码用于读取特定长度的文件: int chunksize = 1024; NSData* fileData = [[NSFileManager defaultManager] contentsAtPath:URL]; NSString* fileName = [[message.fileURL lastPathComponent] stringByDeletingPathExtension]; NSString* extension = [[message.fileU

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

  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!!
int chunksize=1024;
NSData*fileData=[[NSFileManager defaultManager]contentsAtPath:URL];
NSString*fileName=[[message.fileURL lastPathComponent]stringByDeletingPathExtension];
NSString*扩展=[[message.fileURL路径扩展]lastPathComponent];
NSFileHandle*fileHandle=[NSFileHandle fileHandleForReadingAtPath:[自检索文件路径:文件名和扩展名:扩展名]];
文件=@“test.png”;
int numberOfChunks=ceilf(1.0f*[fileData length]/chunksize)//大约800美元

对于(int i=0;i,需要将文件指针设置为要从中读取的偏移量:

[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;
}

什么是
float
s?(
ceilf()
1.0f
)?为了检索文件中的块总数并将实数转换为整数,我使用了这个语法,根本不需要涉及浮点。你有更好的解决方案吗?:)我认为这会起作用:
int numberOfChunks=([fileData length]/chunksize)+([fileData length]%chunksize)?1:0);
这是一个很好的解释方法。非常感谢!!我可以问你为什么选择在[self-seekFile:fileHandler toOffset:2048 error:error]前面使用+吗方法?是否要将其设置为公共类?这是因为这是一个在代码中随处可见的实用类。该类不包含任何状态,只提供实用函数。该类用于创建特定于问题域的自定义
NSError
对象。您只需使用基本
NSError
方法或创建自己的错误生成函数。