C 逐字节顺序比较

C 逐字节顺序比较,c,hash,byte,sequential,deduplication,C,Hash,Byte,Sequential,Deduplication,在c语言中,如何使用xor逐位操作执行逐字节比较?比较两个文件时 #include<stdio.h> int main() { FILE *fp1, *fp2; int ch1, ch2; char fname1[40], fname2[40] ; printf("Enter name of first file :") ; gets(fname1); printf("Enter name of second file:");

在c语言中,如何使用xor逐位操作执行逐字节比较?比较两个文件时

#include<stdio.h>
int main()
{
    FILE *fp1, *fp2;
    int ch1, ch2;
    char fname1[40], fname2[40] ;

    printf("Enter name of first file :") ;
    gets(fname1);

    printf("Enter name of second file:");
    gets(fname2);

    fp1 = fopen( fname1,  "r" );
    fp2 = fopen( fname2,  "r" ) ;

    if ( fp1 == NULL )
       {
       printf("Cannot open %s for reading ", fname1 );
       exit(1);
       }
    else if (fp2 == NULL)
       {
       printf("Cannot open %s for reading ", fname2 );
       exit(1);
       }
    else
       {
       ch1  =  getc( fp1 ) ;
       ch2  =  getc( fp2 ) ;

       while( (ch1!=EOF) && (ch2!=EOF) && (ch1 == ch2))
        {
            ch1 = getc(fp1);
            ch2 = getc(fp2) ;
        }

        if (ch1 == ch2)
            printf("Files are identical n");
        else if (ch1 !=  ch2)
            printf("Files are Not identical n");

        fclose ( fp1 );
        fclose ( fp2 );
       }
return(0);
 }

有什么想法吗?

有很多方法可以做到这一点,如果您将两个文件并排放置,最简单的方法就是并排读取它们并比较缓冲区

#define BUFFERSIZE 4096
FILE *filp1, *filp2;
char *buf1, *buf2;
bool files_equal;
int read1, read2;


filp1 = fopen("file1", "rb");
filp2 = fopen("file2", "rb");

// Don't forget to check that they opened correctly.

buf1 = malloc(sizeof(*buf1)*BUFFERSIZE);
buf2 = malloc(sizeof(*buf2)*BUFFERSIZE);

files_equal = true;

while ( true ) {
    read1 = fread(buf1, sizeof(*buf1), BUFFERSIZE, filp1);
    read2 = fread(buf2, sizeof(*buf2), BUFFERSIZE, filp2);

    if (read1 != read2 || memcmp( buf1, buf2, read1)) { 
         files_equal = false;
         break;
    }
}
如果在读取文件时发生错误,您可能会得到一些误报,但是您可能会为此添加一些额外的检查

另一方面,如果您的文件位于两台不同的计算机上,或者您希望处理大量文件并确定其中是否有相等的文件。最好的方法是使用校验和

好的校验和来自好的散列函数。根据您的安全要求,常见实现使用:

  • SHA-1、SHA-2或SHA-3
  • MD5

还有许多其他问题

那太离题了。无论如何,有很多方法可以比较数据并描述/发现差异/相似之处。这一切都取决于目标…因为(i=0;我感谢你!我尝试使用此程序,但出现以下错误!有什么想法吗?我已在上面编辑的部分下发布了它。我不能说我立即看到错误,你确定test2.txt存在,在其他程序中尚未打开,并且你有权阅读它吗?我将尝试创建另一个文本文件,看看是否有效,谢谢你
#define BUFFERSIZE 4096
FILE *filp1, *filp2;
char *buf1, *buf2;
bool files_equal;
int read1, read2;


filp1 = fopen("file1", "rb");
filp2 = fopen("file2", "rb");

// Don't forget to check that they opened correctly.

buf1 = malloc(sizeof(*buf1)*BUFFERSIZE);
buf2 = malloc(sizeof(*buf2)*BUFFERSIZE);

files_equal = true;

while ( true ) {
    read1 = fread(buf1, sizeof(*buf1), BUFFERSIZE, filp1);
    read2 = fread(buf2, sizeof(*buf2), BUFFERSIZE, filp2);

    if (read1 != read2 || memcmp( buf1, buf2, read1)) { 
         files_equal = false;
         break;
    }
}