iPhone writing binary data

前端 未结 2 1299
猫巷女王i
猫巷女王i 2020-12-10 07:56

How do you write binary data to a file? I want to write floats to a file, raw, and then read them back as floats. How do you do that?

2条回答
  •  误落风尘
    2020-12-10 08:05

    Been experimenting with this:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *file = [documentsDirectory stringByAppendingPathComponent:@"binaryData"];
    
    float b = 32.0f;
    
    NSMutableData *data = [NSMutableData dataWithLength:sizeof(float)];
    [data appendBytes:&b length:sizeof(float)];
    [data writeToFile:file atomically:YES];
    
    NSData *read = [NSData dataWithContentsOfFile:file];
    float b2;
    NSRange test = {0,4};
    [read getBytes:&b2 range:test];
    

    The weird thing is that the file written seems to be 8 bytes and not 4. It is even possible to init the nsdata with 0 length, append a float and then write, and then the file will be 4 bytes. Why is NSData adding 4 bytes by default? A NSData with length 4 should result in a file with length 4, not 8.

提交回复
热议问题