【问题标题】:Append binary data to file将二进制数据附加到文件
【发布时间】:2013-02-22 13:27:05
【问题描述】:

在我的 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 中我看不到有我的文件。怎么了?

【问题讨论】:

    标签: iphone ios5 ios6


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-04
      • 2011-08-05
      • 2011-12-11
      • 2020-10-07
      • 2011-10-13
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多