gpt4 book ai didi

iphone - 将二进制数据附加到文件

转载 作者:行者123 更新时间:2023-12-03 19:43:43 24 4
gpt4 key购买 nike

在我的 iPhone 应用程序中,我需要将二进制数据附加到文件中:

 NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];

NSData* data = [NSData dataWithBytes:buffer length:readBytes_];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"myFile"];

NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
[myHandle seekToEndOfFile];
[myHandle writeData: data];
[myHandle closeFile];
// [data writeToFile:appFile atomically:YES];

// Show contents of Documents directory
NSLog(@"Documents directory: %@",
[fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);

但是在 NSlog 中我没有看到我的文件。怎么了?

最佳答案

如果文件不存在,则 [NSFileHandle fileHandleForUpdatingAtPath:] 将返回 nil (请参阅 docs )。

因此,在尝试打开文件并根据需要创建文件之前请检查:

NSFileManager *fileMan = [NSFileManager defaultManager];
if (![fileMan fileExistsAtPath:appFile])
{
[fileMan createFileAtPath:appFile contents:nil attributes:nil];
}
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
// etc.

并全面添加更多错误检查。

关于iphone - 将二进制数据附加到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15025329/

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