2

此代码应加载 2 个文件并按字节比较它们并输出差异,但由于某种原因,即使使用相同的文件并且似乎忽略了我的格式,它也会输出差异。

任何帮助将不胜感激。

谢谢。

int main(int argc, const char * argv[])
{
    @autoreleasepool {
    NSString *pathA = [[NSBundle mainBundle] pathForResource:@"original/testfile" ofType:@""];
    NSFileHandle *fileA = [NSFileHandle fileHandleForReadingAtPath:pathA];
    NSString *pathB = [[NSBundle mainBundle] pathForResource:@"updated/testfile" ofType:@""];
    NSFileHandle *fileB = [NSFileHandle fileHandleForReadingAtPath:pathB];
    unsigned long long sizeofFile = [fileA seekToEndOfFile];
    [fileA seekToFileOffset:0];
    [fileB seekToFileOffset:0];
    unsigned int fileaValue;
    unsigned int filebValue;
    for (int i = 0; i <= sizeofFile; i++) {
        [[fileA readDataOfLength:1] getBytes:&fileaValue];
        [[fileB readDataOfLength:1] getBytes:&filebValue];
        if (fileaValue != filebValue)
            NSLog(@"File A %02x File B %02x at offset %u:",fileaValue,filebValue,i);
    }
    [fileA closeFile];
    [fileB closeFile];
    }
return 0;
}

示例输出

 2013-03-13 13:50:50.580 compareFile[12055:303] File A 7fce File B 5fbff9ce at offset 0:
 2013-03-13 13:50:50.581 compareFile[12055:303] File A 7ffa File B 5fbff9fa at offset 1:
4

1 回答 1

1

我认为问题可能是您选择的数据类型(如果您想要一个字节,则使用uint8_t),并且几乎可以肯定您<=for循环中的使用:

uint8_t fileaValue;
uint8_t filebValue;
for (unsigned i = 0; i < sizeofFile; i++) {   // NOT <=
    [[fileA readDataOfLength:1] getBytes:&fileaValue];
    [[fileB readDataOfLength:1] getBytes:&filebValue];
    if (fileaValue != filebValue)
        NSLog(@"File A %02x File B %02x at offset %u:", (unsigned)fileaValue, (unsigned)filebValue,i);
}

(请注意NSLog()调用中的强制转换以正确打印值)。

readDataOfLength鉴于文件 I/O 是错误的常见原因,还要检查是否成功。

于 2013-03-13T13:59:43.313 回答