Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare every 1kb of contents of two files instead of character by character

Tags:

c

I'm having this function that compares characters from 2 files, and displays the errors found (line + position).

 void compareFiles(FILE *fp1, FILE *fp2) 
 { 
    char ch1 = getc(fp1); 
    char ch2 = getc(fp2); 
    int error = 0, pos = 0, line = 1; 

    while (ch1 != EOF && ch2 != EOF) 
    { 
        pos++; 

        if (ch1 == '\n' && ch2 == '\n') 
        { 
            line++; 
            pos = 0; 
        } 

        if (ch1 != ch2) 
        { 
            error++; 
            printf("Line Number : %d \tError"
               " Position : %d \n", line, pos); 
        } 

        ch1 = getc(fp1); 
        ch2 = getc(fp2); 
    } 

    printf("Total Errors : %d\t", error); 

But I would like to take every 1kb of data and compare it to another one from file2, because then I want to see how many such blocks are identical. How do I do that?

like image 282
andra Avatar asked May 07 '19 10:05

andra


1 Answers

Read in chunks, so fread not getc.

Then compare in chunks, so strcmp (or memcmp) not char ==.

Don't forget that your inputs may have different lengths (which fread will tell you), so I suggest null-terminating both buffers after your fread, or better yet fail early if the lengths differ.

like image 179
Lightness Races in Orbit Avatar answered Nov 18 '22 21:11

Lightness Races in Orbit