Compare two pictures byte by byte in unix c
while ((c=fgetc(img1)) != EOF)
This reads the first byte from img1
. Assuming it's not EOF
...
fread(&buffer1, 1,1, img1);
This reads the second byte from img1
.
fread(&buffer2, 1,1, img2);
This reads the first byte from img2
.
if(buffer1 != buffer2)
So now we're comparing the first byte of img2
to the second byte of img1
.
If they happen to be equal, we'll go around the loop again, and we'll end up comparing the second byte of img2
to the fourth byte of img1
.
It looks like you might have thought that fgetc
tested to see if there was another byte available, and that fread
then read it. But no. fgetc
reads one character from the file and then returns it. If you write
c = fgetc(fp);
it's almost exactly the same as if you wrote
fread(&c, 1, 1, fp);
So a minimal fix to your program would be to get rid of the
fread(&buffer1, 1,1, img1);
line, and change the equality test to
if(c != buffer2)
But that ends up being kind of confusing -- a later reader is likely to wonder, "why is one file being read using fgetc
, and the other using fread
?"
If I were writing this, I might read one byte from img1
using getc
, and one byte from img2
using getc
, and compare them. Or, I might use fread
to read N bytes from img1
into a character array, and N bytes from img2
into a second character adday, and compare them using the memcmp
function.
Also, as Paul Ogilvie mentioned in a comment, since these are binary files, when you call fopen
to open them you should specify "rb"
mode.
As stated in other comments, the fgetc was reading a char off the stream, so the 2 streams are out of sync before the calls to fread. The following uses 2 calls to fgetc and then uses the return values for the comparison.
void compareFiles(char* path1, char* path2){ FILE* img1; FILE* img2; if((img1 = fopen(path1,"rb")) == NULL || (img2 = fopen(path2,"rb")) == NULL){ printf("ERROR fopen()\n"); exit(-1); } int i=0; int byte1,byte2; while (((byte1=fgetc(img1)) != EOF) && ((byte2=fgetc(img2)) != EOF)){ if(byte1 != byte2){ printf("Byte differs\n IMG1: %c, IMG2: %c; Position %d\n",byte1,byte2,i); i++; } } fclose(img1); fclose(img2);}