一、题目
编写一个程序,比较两个文本文件a1.txt和a2.txt的内容是否相同,若相同则输出“YES”,否则输出“NO”,并输出两个文件内容首次不同的行号和字符位置。
二、程序清单
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef int Status;
#define YES 1
#define NO 0
Status FileCompare(FILE* pfile1, FILE* pfile2, int* row, int* col)
{
*row = 1;
*col = 0;
while (!feof(pfile1) && !feof(pfile2))//若两个文件指针均未指向文件结尾,则进入循环
{
char c1 = fgetc(pfile1);
char c2 = fgetc(pfile2);
++* col;//列数自增
if (c1=='\n'&& c2 == '\n')
{
++* row;//行数自增
*col = 0;//若换行,则字符位置归零
}
if (c1 != c2)//若内容不相同,则跳出循环
break;
}
if (feof(pfile1) && feof(pfile2))//两文件相同
return YES;
else//两文件不同
return NO;
}
int main()
{
FILE* pfile1;
FILE* pfile2;
if ((pfile1 = fopen("a1.txt", "r")) == NULL)
{
printf("文件a1.txt打开失败!");
exit(0);
}
if ((pfile2 = fopen("a2.txt", "r")) == NULL)
{
printf("文件a2.txt打开失败!");
exit(0);
}
int row, col;
if (FileCompare(pfile1, pfile2, &row, &col))//调用函数
{
printf("YES.");
}
else
printf("NO.\n行号:%d\n字符位置:%d", row, col);
if (fclose(pfile1))
{
printf("文件a1.txt无法正常关闭!");
exit(0);
}
if (fclose(pfile2))
{
printf("文件a2.txt无法正常关闭!");
exit(0);
}
return 0;
}
三、运行结果