-3

cでバイトごとの比較を実行するには、xorビットごとの操作をどのように使用しますか? 2 つのファイルを比較する場合

#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);
 }

次の警告が表示され、実行すると、test2.txt が null ですが、データが含まれていると表示されます??

hb@hb:~/Desktop$ gcc -o check check.c
check.c: In function ‘main’:
check.c:21:8: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
check.c:26:8: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
hb@hb:~/Desktop$ 


hb@hb:~/Desktop$ ./check
Enter name of first file :test1.txt
Enter name of second file:test2.txt
Cannot open test2.txt for reading hb@hb:~/Desktop$

何か案は?

4

1 に答える 1

1

これを行うには多くの方法があります。2 つのファイルが並んでいる場合、最も簡単なのは単純にそれらを並べて読み取ってバッファを比較することです。

#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;
    }
}

ファイルの読み取り中にエラーが発生した場合、いくつかの偽陰性が発生する可能性がありますが、おそらくそのための追加のチェックを追加できます。

一方、ファイルが 2 台の異なるコンピューター上にある場合、または多数のファイルを処理してそれらのいずれかが等しいかどうかを調べたい場合。最善の方法は、チェックサムを使用することです。

優れたチェックサムは、優れたハッシュ関数から得られます。セキュリティ要件に応じて、一般的な実装では次を使用します。

  • SHA-1、SHA-2 または SHA-3
  • MD5

他にも多数存在します。ウィキ

于 2014-07-16T22:25:13.757 に答える