Write a program to determine that two binary files are identical. If they are different, prints the first byte at which they differ.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#include <stdint.h>

// structure file io
struct s1 {
	uint8_t a;  // I need a byte used as an integer

int main(int argc, char **argv) {
    struct s1 buf1, buf2;
    int state = 1; // Initially the files are identical
    const char * fn1 = "file1";
    const char * fn2 = "file2";
    FILE *fh1, *fh2;

    fh1 = fopen(fn1, "rb");
    fh2 = fopen(fn2, "rb");

    int rc1, rc2;
    while( (rc1 = fread(&buf1, sizeof(struct s1), 1, fh1)) && (rc2 = fread(&buf2, sizeof(struct s1), 1, fh2))) {

        if (buf1.a != buf2.a) {
            state = 0; // Files not identical
            printf("files %s and %s differ\n", fn1, fn2);
            printf("First byte at which they differ is shown below\n");
            printf("%s: byte %d\n", fn1, buf1.a);
            printf("%s: byte %d\n", fn2, buf2.a);
        printf("files %s and %s are identical\n", fn1, fn2);


    return 0;

When you compile and execute the above program it produces the following result on Linux:

/* Case1: Running the program with identical files */
$ ./6.1
files file1 and file2 are identical

/* Case2: Running the program with unidentical files */
$ ./6.1
files file1 and file2 differ
First byte at which they differ is shown below
file1: byte 73
file2: byte 10

Brief Explanation

  • The program starts by opening two test files, file1 and file2 in binary mode for reading.
  • Using a while loop, a byte by byte comparison is made and stop as soon as a mismatch is found. The first byte at which they differ is printed.
  • If no mismatch was found, then the files are identical in which case the state is 1 and the last printf function is executed.


Add comment

Security code