copying the contents of a binary file

I am designing an image decoder and as a first step I tried to just copy the using c. i.e open the file, and write its contents to a new file. Below is the code that I used.

while((c=getc(fp))!=EOF)
  fprintf(fp1,"%c",c);

where fp is the source file and fp1 is the destination file. The program executes without any error, but the image file(".bmp") is not properly copied. I have observed that the size of the copied file is less and only 20% of the image is visible, all else is black. When I tried with simple text files, the copy was complete.

Do you know what the problem is?


Solution 1:

Make sure that the type of the variable c is int, not char. In other words, post more code.

This is because the value of the EOF constant is typically -1, and if you read characters as char-sized values, every byte that is 0xff will look as the EOF constant. With the extra bits of an int; there is room to separate the two.

Solution 2:

Did you open the files in binary mode? What are you passing to fopen?