I'm trying to compare two files to find where they differ using read and write commands and I'm going off a book's example in some sense and think I got the compare function right but I obviously don't because the sprintf functions print out. My best guess is how I'm comparing the two files?:
(updated code)
Byte pos where two files differ is:
Byte value of file 1: %o
Byte value of file 2: %o
void compare_two_binary_files(int f1, int f2)
{
write(1, sprintf, 10);
ssize_t byte_read_f1, byte_read_f2, length, numRead, bob;
char buf1[BUF_SIZE], buf2[BUF_SIZE], a[100], b[100], counter[100];
int count = 0, b_pos1, b_pos2;
while ((byte_read_f1 = read(f1, buf1, sizeof buf1) > 0) && (byte_read_f2 = read(f2, buf2, sizeof buf2) >0)) {
ssize_t len = byte_read_f1 <byte_read_f2 ? byte_read_f1 : byte_read_f2;
if (memcmp(buf1, buf2, len) != 0){
ssize_t i;
sprintf(counter, "Byte pos where two files differ is:%lld\n", (long long) count + i);
sprintf(a, "Byte value of file 1: %hho\n", buf1[i]);
sprintf(b, "Byte value of file 2: %hho\n", buf2[i]);
break;
}
count += len;
}
New code but still error with not going through the if "!=" statement because it simply doesn't go through it when I want it to. Help please:
void compare_two_binary_files(int f1, int f2)
{
ssize_t byte_read_f1, byte_read_f2, length, i;
char buf1[BUF_SIZE], buf2[BUF_SIZE], a[BUF_SIZE], b[100], counter[100];
int count = 0;
while ((byte_read_f1 = read(f1, buf1, BUF_SIZE) > 0) && (byte_read_f2 = read(f2, buf2, BUF_SIZE) >0)){
if (byte_read_f1 != byte_read_f2){
sprintf(counter, "Byte pos where two files differ is:%lld\n", (long long) count + 1);
sprintf(a, "Byte value of file 1: %o\n", buf1[i]);
sprintf(b, "Byte value of file 2: %o\n", buf2[i]);
write(1, counter, 100);
write(1, a, 100);
write(1, b, 100);
}
i++;
count++;
}
}
I'm here now. And it's not going into the if (memcmp(buf1, buf2, len) != 0){
:
void compare_two_binary_files(int f1, int f2)
{
//write(1, sprintf, 10);
ssize_t byte_read_f1, byte_read_f2, length, numRead, bob;
char buf1[BUF_SIZE], buf2[BUF_SIZE], a[100], b[100], counter[100];
int count = 0, b_pos1, b_pos2, hey;
while ((byte_read_f1 = read(f1, buf1, sizeof buf1) > 0) && (byte_read_f2 = read(f2, buf2, sizeof buf2) >0)) {
ssize_t len = byte_read_f1 <byte_read_f2 ? byte_read_f1 : byte_read_f2;
if (memcmp(buf1, buf2, len) != 0){
ssize_t i;
for (i = 0; i<len; i++){
if (buf1[i] != buf2[i]) break;
}
sprintf(counter, "Byte pos where two files differ is:%lld\n", (long long) count + i);
write(1, counter, 100);
sprintf(a, "Byte value of file 1: %hho\n", buf1[i]);
sprintf(b, "Byte value of file 2: %d\n", buf2[i]);
write(1, counter, 100);
write(1, b, 100);
write(1, a, 100);
break;
}
count += len;
}
}
When I change the !=
of memcmp to ==
it works but gives me wrong numbers. I'm supposed to get byte location 4, file 1 to be 65 and file 2 to be 143, but get pos 1, file 1 is 163 and file 2 is 115