1

I have the following code for reading a file in length of specific size:

  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!!
just ME
  • 1,817
  • 6
  • 32
  • 53

1 Answers1

4

You need to set the file pointer to the offset you want to read from:

[fileHandle seekToFileOffset:2048];

And then read the data:

NSData *data = [fileHandle readDataOfLength:1024];

Be aware that errors are reported in the form of NSExceptions, so you'll want some @try/@catch blocks around most of these calls. In fact the use of exceptions to report errors means I often make my own file-access functions to ease their use; for example:

+ (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;
}
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • a very nice way of explaining this. Thank you very much!! Could I ask you why did you choose to use + in front of the [self seekFile:fileHandler toOffset:2048 error:error] method? You want to make it a public one? – just ME Jul 17 '14 at 07:31
  • It's because that's a utility class which is used from everywhere in the code. The class holds no state and simply provides utility functions. – trojanfoe Jul 17 '14 at 07:32
  • That's a class to create custom `NSError` objects, specific to the problem domain. You can just use the base `NSError` methods or create your own error-generating functions. – trojanfoe Jul 17 '14 at 08:00