12

Are there good examples for doing file read/write in chunks with objective c? I am new to objective-c and iPhone API, here is the sample code that I wrote. Are there better ways to do it?

-(void) performFileOperation
{
    @try {

        NSFileHandle *inputFileHandle;
        NSFileHandle *outputFileHandle;

        //check whether the output file exist, if not create a new one.
        NSFileManager *morphedFileManager;

        outputFileManager = [NSFileManager defaultManager];

        if ([outputFileManager fileExistsAtPath: self.outputFilePath ] == NO)
        {
            NSLog (@"Output file does not exist, creating a new one");
            [outputFileManager createFileAtPath: self.outputFilePath
                                        contents: nil
                                      attributes: nil];
        }

        NSData *inputDataBuffer;

        inputFileHandle = [NSFileHandle fileHandleForReadingAtPath: self.inputFilePath];

        NSAssert( inputFileHandle != nil, @"Failed to open handle for input file" );

        outputFileHandle  = [NSFileHandle fileHandleForReadingAtPath: self.outputFilePath];

        NSAssert( outputFileHandle != nil, @"Failed to open handle for output file" );

        @try{
            // seek to the start of the file
            [inputFileHandle seekToFileOffset: 0];
            [outputFileHandle seekToFileOffset: 0];

            while( (inputDataBuffer = [inputFileHandle readDataOfLength: 1024]) != nil )
            {
                [outputFileHandle writeData: [self.fileWrapper process: inputDataBuffer]];
            }
        }
        @catch (NSException *exception) {
            @throw;
        }
        @finally {
            [inputFileHandle closeFile];
            [outputFileHandle closeFile];
        }        
    }
    @catch (NSException *exception) {
        @throw;
    }
}

I get the following exception while trying to write:

Failed to process input buffer ( *** -[NSConcreteFileHandle writeData:]: Bad file descriptor )
ssk
  • 9,045
  • 26
  • 96
  • 169
  • Does this work? It seems fine at first glance. Maybe you could increase the buffer size to something like 65kB or whatever. –  Apr 25 '13 at 20:47
  • looks like i was using fileHandleForReadingAtPath instead of fileHandleForWritingAtPath. – ssk Apr 25 '13 at 21:06

1 Answers1

3

Needs to change outputFileHandle line:

 outputFileHandle  = [NSFileHandle fileHandleForWritingAtPath: self.outputFilePath];
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
ssk
  • 9,045
  • 26
  • 96
  • 169