您的位置:首页 > Web前端

Compare to files,printing the first line where they differ

2012-07-09 16:49 169 查看
#include<stdio.h>

# define SIZE 100

int compareTxt(FILE *fp1,FILE *fp2);
void show_file(char *name);

int main()
{
FILE *fp1 = fopen("txt1.txt","r");
FILE *fp2 = fopen("txt2.txt","r");
/*place the pointer to the beginning of the file,which point to the file*/
rewind(fp1);
rewind(fp2);
//show_file("txt2.txt");
compareTxt(fp1,fp2);
return 0;
}

int compareTxt(FILE *fp1,FILE *fp2)
{
char c1,c2;
char *line = new char[SIZE];
while(!feof(fp1) && !feof(fp2))
{
if((c1=fgetc(fp1)) != (c2 = fgetc(fp2)))
{
fgets(line,SIZE,fp1);
printf("File 1:%c%s\n",c1,line);
fgets(line,SIZE,fp2);
printf("File 2:%c%s\n",c2,line);
break;
}
}
if(c1 == EOF && c2 == EOF)
{
printf("Two files are the same.");
fclose(fp1);
fclose(fp2);
return 1;
}
else if(c1 != EOF && c2 == EOF)
{
fgets(line,SIZE,fp1);
fclose(fp1);
fclose(fp2);
printf("%s \n",line);
return -1;
}
else
{
fgets(line,SIZE,fp2);
fclose(fp1);
fclose(fp2);
printf("%s \n",line);
return -1;
}
}

void show_file(char *name)
{
FILE *fp = fopen(name,"r");
char c;
while((c = fgetc(fp)) != EOF)
{
printf("%c",c);
}
fclose(fp);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  printing fp file c