首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用NSFileHandle读/写文件的示例

使用NSFileHandle读/写文件的示例
EN

Stack Overflow用户
提问于 2013-04-26 04:46:20
回答 1查看 17.3K关注 0票数 12

有没有很好的例子可以用objective c对文件进行块读写?我是objective-c和iPhone应用编程接口的新手,下面是我写的示例代码。有没有更好的方法呢?

代码语言:javascript
复制
-(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;
    }
}

在尝试编写代码时,我遇到了以下异常:

代码语言:javascript
复制
Failed to process input buffer ( *** -[NSConcreteFileHandle writeData:]: Bad file descriptor )
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-26 05:07:29

需要更改outputFileHandle行:

代码语言:javascript
复制
 outputFileHandle  = [NSFileHandle fileHandleForWritingAtPath: self.outputFilePath];
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16224389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档