这是我的一个小方法:
void CompareTwoFiles(FILE *fp1, FILE *fp2){
char ch1, ch2;
int flag = 0;
//must seek first to determine the sizes
fseek (fp1, 0, SEEK_END);
fseek (fp2, 0, SEEK_END);
if(ftell(fp1) != ftell(fp2)){
printf("The sizes of the files are different so they cannot be equal.\n");
return;
}
while (((ch1 = fgetc(fp1)) != EOF) &&((ch2 = fgetc(fp2)) != EOF))
{
/*
* character by character comparision
* if equal then continue by comparing till the end of the files
*/
if (ch1 == ch2)
{
flag = 1;
continue;
}
//If not equal then return the byte position
else
{
fseek(fp1, -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(fp1)+1);
printf("First file contains %c and second file contains %c \n", ch1, ch2); //ISSUE: prints blank for ch1 and ch2
}
else
{
printf("Two files are Equal\n ", ftell(fp1)+1);
}
}
我很想在printf中打印我用fgetc分配的两个字符。但相反,我得到了空白。输出如下:
第一个文件包含,第二个文件包含
有人可以指出我出错的地方。我对C和C ++有点生疏。
答案 0 :(得分:1)
首先修复警告。
$ gcc main.c
main.c: In function ‘CompareTwoFiles’:
main.c:37:12: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
printf("Two files are not equal : byte position at which two files differ
^
main.c:42:12: warning: too many arguments for format [-Wformat-extra-args]
printf("Two files are Equal\n ", ftell(fp1)+1);
获得一个干净的编译并只回放文件,您会看到您的代码有效。你的代码没有倒回,所以你不知道你得到了哪个char
。
#include <stdio.h>
void CompareTwoFiles(FILE *fp1, FILE *fp2) {
char ch1, ch2;
int flag = 0;
//must seek first to determine the sizes
fseek(fp1, 0, SEEK_END);
fseek(fp2, 0, SEEK_END);
if (ftell(fp1) != ftell(fp2)) {
printf("The sizes of the files are different so they cannot be equal.\n");
return;
}
rewind(fp1);
rewind(fp2);
while (((ch1 = fgetc(fp1)) != EOF) && ((ch2 = fgetc(fp2)) != EOF)) {
/*
* character by character comparision
* if equal then continue by comparing till the end of the files
*/
if (ch1 == ch2) {
flag = 1;
continue;
}
//If not equal then return the byte position
else {
fseek(fp1, -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", (int) ftell(fp1) + 1);
printf("First file contains %c and second file contains %c \n", ch1, ch2); //ISSUE: prints blank for ch1 and ch2
}
else {
printf("Two files are Equal %d\n ", (int) ftell(fp1) + 1);
}
}
int main() {
FILE *fp;
fp = fopen("tmp.txt", "r");
FILE *fp2;
fp2 = fopen("tmp2.txt", "r");
CompareTwoFiles(fp, fp2);
return 0;
}
<强> tmp.txt 强>
1 1 23 2134 123 12321
123
42
<强> tmp2.txt 强>
0 1 23 2134 123 12321
123
42
<强>输出强>
$ ./a.out
Two files are not equal : byte position at which two files differ is 1.
First file contains 1 and second file contains 0