将二进制数据附加到文件

时间:2013-02-22 13:27:06

标签: iphone ios5 ios6

在我的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中我没有看到我的文件。有什么问题?

1 个答案:

答案 0 :(得分:3)

如果文件不存在,则[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.

全面添加更多错误检查。