Search code examples
cfilebinarystrcmp

compare two binary files using strcmp() in c Language


Sorry for my bad English first.

I have two binary files.

And I store binary into buffer respectively.

Then I compared two buffer using strcmp().

Result of strcmp() is zero.

So I think two binary is identical.

Open two binary and then checked if there are no differences.

But I can find little difference.

what is the problem?

strcmp() function doesn't proper way to compare binary to binary?


Solution

  • The C function strcmp is written to compare strings. In C, strings are char pointers or arrays, that end with a null byte ('\0'). Therefore, the comparison only goes up to the first null byte.

    Example:

    File A: "abcd\0efg" File B: "abcd\0xyz"

    Since both files are equal up to the null byte, the "strings" at these locations are equal, although what comes after may differ. You should use the function memcmp instead (see this tutorial; see examples from the reference).

    EDIT: As pointed out by the comment under this answer and as mentioned in the other answer, the man pages of strcmp and memcmp are reliable resources to learn about these function from the standard library.