首頁  >  文章  >  後端開發  >  C程式比較兩個文件並報告不匹配

C程式比較兩個文件並報告不匹配

WBOY
WBOY轉載
2023-09-17 17:29:02930瀏覽

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.

Example

的中文翻譯為:

範例

#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 == &#39;</p><p>&#39; && ch2 == &#39;</p><p>&#39;){
         line++;
         pos = 0;
      }
      if (ch1 != ch2){
         error++;
         printf("Line Number : %d \tError"
         " Position : %d </p><p>", 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

以上是C程式比較兩個文件並報告不匹配的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除