比较两个文本文件是否相等: 比较两个文本文件的内容是否相同,并输出两个文件中第一次出现不同字符内容的行号及列值。试编写相应程序。
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
FILE *fp1,*fp2;
char ch1,ch2;
int cnt_row=1,cnt_column=0,flag=1; //flag用于标志是否有不同的地方,默认相同
//行号row每次遇到‘\n’时++;列号每次读入一个字符++,换行后清零
if((fp1 = fopen("test3.1.txt","r"))==NULL||(fp2 = fopen("test3.2.txt","r"))==NULL){
printf("file read error\n");
exit(0);
}
while( ( (ch1=fgetc(fp1) )!=EOF) &&( (ch2=fgetc(fp2)) !=EOF) ){
cnt_column++;
if(ch1 != ch2){
printf("not equal! %d row,%d column\n",cnt_row,cnt_column);
flag = 0; //遇到了不同的字符,改变flag
break; //保证只输出第一个不同的字符
}
if(ch1=='\n'){
cnt_row++;
cnt_column = 0;
}
}
if(flag)
printf("both files are the same\n");
return 0;
}