📜  C程序比较两个文件并报告不匹配

📅  最后修改于: 2021-05-25 19:10:10             🧑  作者: Mango

我们得到了几乎两个相同的文件。但是某些字符已损坏。我们需要找到行号及其在这些损坏的字母所在的位置以及损坏(错误)字母的总数。

例子:

Input :
file1.txt contains
it is
fun
file2.txt contains
it is
run

Output :
Line Number : 2         Error Position : 1
Total Errors : 1

先决条件:C语言中的getc()

脚步 :
1.>在只读模式下使用文件指针打开两个文件。
2.>逐个读取两个char变量中的文件数据,直到文件结束。
3.>如果变量遇到新行,则增加行号并将位置重置为零。
4.>如果变量不相等,则增加错误数并打印错误行以及错误索引。

// C program to compare two files and report
// mismatches by displaying line number and
// position of line.
#include
#include
#include
  
void compareFiles(FILE *fp1, FILE *fp2)
{
    // fetching character of two file
    // in two variable ch1 and ch2
    char ch1 = getc(fp1);
    char ch2 = getc(fp2);
  
    // error keeps track of number of errors
    // pos keeps track of position of errors
    // line keeps track of error line
    int error = 0, pos = 0, line = 1;
  
    // iterate loop till end of file
    while (ch1 != EOF && ch2 != EOF)
    {
        pos++;
  
        // if both variable encounters new
        // line then line variable is incremented
        // and pos variable is set to 0
        if (ch1 == '\n' && ch2 == '\n')
        {
            line++;
            pos = 0;
        }
  
        // if fetched data is not equal then
        // error is incremented
        if (ch1 != ch2)
        {
            error++;
            printf("Line Number : %d \tError"
               " Position : %d \n", line, pos);
        }
  
        // fetching character until end of file
        ch1 = getc(fp1);
        ch2 = getc(fp2);
    }
  
    printf("Total Errors : %d\t", error);
}
  
// Driver code
int main()
{
    // opening both file in read only mode
    FILE *fp1 = fopen("file1.txt", "r");
    FILE *fp2 = fopen("file2.txt", "r");
  
    if (fp1 == NULL || fp2 == NULL)
    {
       printf("Error : Files not open");
       exit(0);
    }
  
    compareFiles(fp1, fp2);
  
    // closing both file
    fclose(fp1);
    fclose(fp2);
    return 0;
}

输出:

Line Number : 2         Error Position : 1
Total Errors : 1

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。