user2165702
user2165702

Reputation: 21

objective C Comparing 2 files bytewise

This code should load 2 files and compare them byte wise and output the differences , but for some reason it outputs a difference even if the same file is used and seems to be ignoring my formatting.

Any help would be greatly appreciated.

Thanks.

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;
}

Example output

 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:

Upvotes: 2

Views: 226

Answers (1)

trojanfoe
trojanfoe

Reputation: 122391

I think the issue is possibly the data types you have chosen (if you want a single byte then use uint8_t) and almost certainly your use of <= in the for loop:

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);
}

(Note the cast in the NSLog() call to make that print the values correctly).

Also checking the success of the readDataOfLength is in order given File I/O is a common cause of error.

Upvotes: 1

Related Questions