我尝试读取2个二进制文件并检查一个文件是否至少包含第二个文件的内容(不一定完全相同)。
我曾尝试过:
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *file1, *file2;
file1 = fopen(argv[1], "rb");
file2 = fopen(argv[2], "rb");
if(file1 == NULL)
{
printf("Error: can't open file number one.\n");
}
if(file2 == NULL)
{
printf("Error: can't open file number two.\n");
}
else
{
/* if the files can open... start to check... */
}
}
答案 0 :(得分:1)
您可以逐个字符地比较2个文件(如果它的二进制文本或文本不重要),并使用逐步浏览2个文件并逐个字符比较的函数。
#include <stdio.h>
void compare(FILE *, FILE *);
int main(int argc, char *argv[]) {
FILE *file1, *file2;
file1 = fopen(argv[1], "r");
if (file1 == NULL) {
printf("Error: can't open file number one.\n");
return 0;
}
file2 = fopen(argv[2], "r");
if (file2 == NULL) {
printf("Error: can't open file number two.\n");
return 0;
}
if ((file1 != NULL) && (file2 != NULL)) {
compare(file1, file2);
}
}
/*
* compare two binary files
*/
void compare(FILE *file1, FILE *file2) {
char ch1, ch2;
int flag = 0;
while (((ch1 = fgetc(file1)) != EOF) && ((ch2 = fgetc(file2)) != EOF)) {
/*
* if equal then continue by comparing till the end of files
*/
if (ch1 == ch2) {
flag = 1;
continue;
}
/*
* If not equal then returns the byte position
*/
else {
fseek(file1, -1, SEEK_CUR);
flag = 0;
break;
}
}
if (flag == 0) {
printf("Two files are not equal : byte position at which two files differ is %d\n", ftell(file1) + 1);
}
else {
printf("Two files are Equal\n");
}
}
测试
$ ./a.out a.out a2.out
Two files are not equal : byte position at which two files differ is 209
$ cp a.out a2.out
$ ./a.out a.out a2.out
Two files are Equal