2013-02-22 112 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. 

,並添加更多的錯誤檢查全面。