NSFileHandle的文件读写示例

13

有没有使用Objective-C以块的方式进行文件读写的好例子?我刚接触Objective-C和iPhone API,这是我编写的示例代码。有更好的方法吗?

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

我在尝试写入时遇到了以下异常:

Failed to process input buffer ( *** -[NSConcreteFileHandle writeData:]: Bad file descriptor )

这个能用吗?乍一看似乎没问题。也许你可以把缓冲区大小增加到65kB或其他什么值。 - user529758
我看起来是在使用 fileHandleForReadingAtPath 而不是 fileHandleForWritingAtPath。 - ssk
1个回答

4

需要更改outputFileHandle这一行:

 outputFileHandle  = [NSFileHandle fileHandleForWritingAtPath: self.outputFilePath];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接