Scripting‎ > ‎C examples‎ > ‎

Compare file char by char in C

Thank you for visiting this page, this page has been update in another link Compare file char by char in C

Compare file char by char in c

For text file, better to use diff, but for binary file or compressed file, I have a c code.

Here is an example C code I wrote to compare two files char by char, to check where the file got corrupted.

#include <stdlib.h>
#include <stdio.h>
#include<sys/stat.h>

int file_exists (char * fileName)
{
   struct stat buf;
   int i = stat ( fileName, &buf );
     /* File found */
     if ( i == 0 )
     {
       return 1;
     }
     return 0;
      
}
int main(int argc, char *argv[])
{
    FILE *pFile1;
    FILE *pFile2;
    long int cnt_good=0;
    long int cnt_bad=0;
    long int cnt_total=0;
    long int cnt_k=0;
    long int cnt_good_k=0;
    char *file1;
    char *file2;

    if( argc < 3 )
    {
        printf("Usage: \n %s <file1> <file2>\n\n",argv[0]);
        exit(0);
    }
    file1=argv[1];
    file2=argv[2];
    if(! ( ( file_exists(file1) && file_exists(file2) ) ) ) {
        printf("\nFile '%s' or '%s'  not found!\n Usage: \n %s <file1> <file2>\n\n",argv[1],argv[2],argv[0]);
        exit(0);
    }

    pFile1= fopen(file1, "r");
    pFile2= fopen(file2, "r");

    while(!(feof(pFile1) || feof(pFile2) ))
    {
        cnt_total++;
        if(cnt_total >= 1000)
        {
            cnt_total=cnt_total-1000;
            cnt_k++;
                }
        if( fgetc( pFile1) == fgetc( pFile2) )
        {
            cnt_good++;
            if(cnt_good >= 1000)
            {
                cnt_good=cnt_good-1000;
                cnt_good_k++;
                    }
        }
        else
        {
            cnt_bad++;
            printf("found one of %d corrupted characters at position %dk %d\n", cnt_bad,cnt_k,cnt_total);
        }
    }

    fclose(pFile1);
    fclose(pFile2);
    printf("total %dk+%d characters where compared, good characters %d+%d,while corrupted characters are %d\n",cnt_k,cnt_total,cnt_good_k,cnt_good,cnt_bad);
}

Comments