我的目标是做一个函数来告诉两个不同的文件是否相同(它们包含相同的内容)。
这是我的代码:
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)
成立。为什么会发生这种情况?谢谢。
1条答案
按热度按时间hivapdat1#
您没有检查正确的缓冲区长度。请尝试