用C语言判断两个文件是否相同,但不能判断该算法的谬误

zbq4xfa0  于 2023-04-19  发布在  其他
关注(0)|答案(1)|浏览(103)

我的目标是做一个函数来告诉两个不同的文件是否相同(它们包含相同的内容)。
这是我的代码:

int are_files_equal(char* filename1, char* filename2){  
if(strcmp(filename1, filename2) == 0)
        return 1;

    struct stat stat1, stat2;

    if ( stat(filename1, &stat1) != 0 || stat(filename2, &stat2) != 0)
        return -1; // error opening files

    if(stat1.st_size != stat2.st_size)
        return 0; // files are not the same as they have a different dimension
    
    FILE *file1 = fopen(filename1, "rb");
    FILE *file2 = fopen(filename2, "rb");
    if (file1 == NULL || file2 == NULL)
    {
        return -1; // error opening files
    }
    #define BYTES_TO_READ_AT_ONCE 512000
    unsigned char databuffer1[BYTES_TO_READ_AT_ONCE];
    unsigned char databuffer2[BYTES_TO_READ_AT_ONCE];
    size_t bytes;
    while ((fread(databuffer1, 1, BYTES_TO_READ_AT_ONCE, file1)) != 0)
    {
        fread(databuffer2, 1, BYTES_TO_READ_AT_ONCE, file2);
        if(memcmp(databuffer1, databuffer2, BYTES_TO_READ_AT_ONCE) != 0)
            return 0;
    }
    fclose(file1);
    fclose(file2);
    return 1;
}

但是由于某些原因我不能理解,它失败了。特别是if(memcmp(databuffer1, databuffer2, BYTES_TO_READ_AT_ONCE) != 0)成立。为什么会发生这种情况?谢谢。

hivapdat

hivapdat1#

您没有检查正确的缓冲区长度。请尝试

size_t bytes;
bool matching = true;
while ((bytes = fread(databuffer1, 1, BYTES_TO_READ_AT_ONCE, file1)) != 0)
{
    if(bytes != fread(databuffer2, 1, BYTES_TO_READ_AT_ONCE, file2) ||
            memcmp(databuffer1, databuffer2, bytes) != 0) {
        matching = false;
        break;
    }
}

if(fread(databuffer2, 1, BYTES_TO_READ_AT_ONCE, file2) != 0) {
    matching = false;    // check if the whole file was read
}
fclose(file1);
fclose(file2);
return matching;

相关问题