2013-02-22 109 views
3

在我的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的我没有看到有我的文件。哪里不对?

回答

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. 

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