C 程式比較兩個檔案並報告不匹配項


在 C 程式語言中,程式設計師可訪問檔案並讀寫其中的內容。

檔案是一種可儲存資訊的簡單記憶體塊,在此,我們僅關注文字。

在本程式中,我們將比較兩個檔案並報告發生的差異。這些檔案幾乎相同,但可能含有一些不同的字元。此外,程式將返回第一個差異發生的檔案的行和位置。

演算法

Step 1: Open both the file with pointer at the starting.
Step 2: Fetch data from file as characters one by one.
Step 3: Compare the characters. If the characters are different then return the line and position of the error character.

示例

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void compareFiles(FILE *file1, FILE *file2){
   char ch1 = getc(file1);
   char ch2 = getc(file2);
   int error = 0, pos = 0, line = 1;
   while (ch1 != EOF && ch2 != EOF){
      pos++;
      if (ch1 == '
' && ch2 == '
'){          line++;          pos = 0;       }       if (ch1 != ch2){          error++;          printf("Line Number : %d \tError"          " Position : %d
", line, pos);       }       ch1 = getc(fp1);       ch2 = getc(fp2);    }    printf("Total Errors : %d\t", error); } int main(){    FILE *file1 = fopen("file1.txt", "r");    FILE *file2 = fopen("file2.txt", "r");    if (file1 == NULL || file2 == NULL){       printf("Error : Files not open");       exit(0);    }    compareFiles(file1, file2);    fclose(file1);    fclose(file2);    return 0; }

輸出

// content of the files
File1 : Hello!
Welcome to tutorials Point
File2: Hello!
Welcome to turoials point
Line number: 2 Error position: 15
Total error : 1

更新於: 19-Sep-2019

8K+ 瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.