[英]Example for file read/write with NSFileHandle
Are there good examples for doing file read/write in chunks with objective c? 是否有使用目标c进行文件读/写的好例子? I am new to objective-c and iPhone API, here is the sample code that I wrote.
我是objective-c和iPhone API的新手,这是我写的示例代码。 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 )
需要更改outputFileHandle
行:
outputFileHandle = [NSFileHandle fileHandleForWritingAtPath: self.outputFilePath];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.