Home >Backend Development >C++ >C program compares two files and reports a mismatch

C program compares two files and reports a mismatch

WBOY
WBOYforward
2023-09-17 17:29:02999browse

C program compares two files and reports a mismatch

In the C programming language, programmers can access files and read and write their contents.

A file is a simple block of memory that can store information, we only care about text.

In this program we will compare two files and report any mismatches that occur. These files are almost identical, but may have some character differences. Additionally, the program returns the line and position of the file where the first mismatch occurs. The Chinese translation of

Algorithm

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

is:

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;
}

Output

// 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

The above is the detailed content of C program compares two files and reports a mismatch. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete