object-c nsdata 读取和写入二进制文件

-(void)test_file{

    // 获取程序Documents目录路径

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    

    NSMutableString * path = [[NSMutableString alloc]initWithString:documentsDirectory];

    [path appendString:@"/fuck"];

    NSString *temp = @"我现在要告诉我那你哈哈哈len 是不是Dang";

    NSInteger i = [[temp dataUsingEncoding:NSUTF8StringEncoding] length];

    

    NSMutableData * data = [[NSMutableData alloc]init];

    [data appendBytes:&i length:sizeof(i)];

    [data appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];

    

    

    

    [data writeToFile:path atomically:YES];

    

    

    NSInteger fuck = 0;

    NSString * fff ;

    NSData * reader = [NSData dataWithContentsOfFile:path];

    [reader getBytes:&fuck length:sizeof(fuck)];

   

    fff = [[NSString alloc] initWithData:[reader subdataWithRange:NSMakeRange(sizeof(fuck) , fuck)]

                                  encoding:NSUTF8StringEncoding];

    NSLog(@"%@" , fff);

    [fff release];

    [path release];

    [data release];

}

你可能感兴趣的:(ios)