【发布时间】:2014-01-29 22:46:21
【问题描述】:
我正在尝试使用读写命令比较两个文件以找出它们的不同之处,并且在某种意义上我要离开一本书的示例,并认为我的比较功能是正确的,但我显然没有,因为 sprintf功能打印出来。我最好的猜测是我如何比较这两个文件?:
(更新代码)
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;
}
新代码,但由于没有通过 if "!=" 语句仍然出错,因为它根本没有在我想要的时候通过它。请帮忙:
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++;
}
}
我现在在这里。而且它不会进入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;
}
}
当我将 memcmp 的 != 更改为 == 时,它可以工作,但给了我错误的数字。我应该得到字节位置 4,文件 1 是 65,文件 2 是 143,但是得到 pos 1,文件 1 是 163,文件 2 是 115
【问题讨论】:
-
首先阅读
read。 1. 您正在将两个文件中的 n 个字节读取到同一个缓冲区中——在测试时,它们总是“相同的”。 2.您正在比较读取的字节数。 3. 不能使用==比较char数组。 -
@Jongware 比较读取的字节数很好,只是还需要后续的
memcmp()正确读取的缓冲区。 -
请一致地缩进你的代码
-
@chux:当然,但似乎 OP 希望这也能以某种方式比较字节。 OP:chux 的意思是如果
byte_read_f1 != byte_read_f2那么你不必比较——读取的字节数不同,所以文件在那个点上不同。 -
@chux - 所以循环的 buf、BUF 部分没问题,只是你说的 memcmp()?