gpt4 book ai didi

objective-c - 使用 NSFileHandle 读取/写入文件的示例

转载 作者:太空狗 更新时间:2023-10-30 03:22:21 30 4
gpt4 key购买 nike

是否有使用 objective c 进行文件 block 读/写的好例子?我是 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];

关于objective-c - 使用 NSFileHandle 读取/写入文件的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16224389/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com