-1

I want to count the 1kb blocks of 2 files and print out the number of identical blocks of these 2 files. I tried to read with fread 1kb blocks but when I tried to compare them I got stuck. I tried to compare the 1 kb blocks with strcmp but that won't work because strcmp is expecting a const char*, is there a way to convert a size_t to a const char*? or is there a better way to compare the blocks? So fare I wrote this:

#include <stdio.h>
#include <string.h>
int main()
{
    FILE *fin;
    FILE *fin2;
    char block[1024];
    char block2[1024];
    int result;
    int count=0;
    int count_b_file1=0;
    int  count_b_file2=0;
    fin=fopen("file1","r");
    fin2=fopen("file2","r");
    size_t s_file1;
    size_t s_file2;
    while( (! feof(fin)) && (! feof(fin2))){
        s_file1=fread(block,1,sizeof(block),fin);
        count_b_file1=count_b_file1+1;
        s_file2=fread(block2,1,sizeof(block2),fin2);
        count_b_file2=count_b_file2+1;
        result=strcmp(s_file1,s_file2);
        if (result==0){
            count=count+1;
        }
    }
    fclose(fin);
    fclose(fin2);
    return 0;
}
abelenky
  • 63,815
  • 23
  • 109
  • 159
newhere
  • 31
  • 5
  • 1
    I think you want `memcmp`, not `strcmp`. – abelenky Apr 22 '21 at 19:32
  • [“while ( !feof (file) )” is always wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – KamilCuk Apr 22 '21 at 19:32
  • Wait.... you're calling `strcmp` with two variables of type `size_t`??? How does that make ***any*** sense? What are you trying to do there? – abelenky Apr 22 '21 at 19:37
  • After applying the `memcmp` fix [as suggested by others], your code assumes that both files have exactly the same length. Just before the [new] `memcmp` line, you may want: `if (s_file1 != s_file2) break;` You can only get unequal lengths if one file is shorter than the other. And, when you hit that point [in the shorter file], you can never get a further match, so you should stop the loop. – Craig Estey Apr 22 '21 at 21:08

1 Answers1

0

strcmp is only for comparing NUL-terminated strings. Do you have any reason to know that your 1Kb blocks are NUL-terminated strings? If there happens to be a 0x00 byte in the first few bytes of your block, strcmp will end prematurely!

memcmp will do byte-level comparison of the entire blocks.

abelenky
  • 63,815
  • 23
  • 109
  • 159