objective-c – 使用NSFileHandle进行文件读取/写入的示例
发布时间:2020-12-16 05:29:08 所属栏目:百科 来源:网络整理
导读:有没有很好的例子来做文件读/写与块c与客观c?我是 Objective-c和iPhone API的新手,这里是我写的示例代码.有更好的方法吗? -(void) performFileOperation{ @try { NSFileHandle *inputFileHandle; NSFileHandle *outputFileHandle; //check whether the out
有没有很好的例子来做文件读/写与块c与客观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 ) 解决方法
需要更改outputFileHandle行:
outputFileHandle = [NSFileHandle fileHandleForWritingAtPath: self.outputFilePath]; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |