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?
Make sure that the type of the variable
c
isint
, notchar
. In other words, post more code.This is because the value of the
EOF
constant is typically -1, and if you read characters aschar
-sized values, every byte that is0xff
will look as the EOF constant. With the extra bits of anint
; there is room to separate the two.It's one of the most "popular" C gotchas.
You should use
fread
andfwrite
using a block at a timeIt's substantially faster to read in bigger blocks, and fread/fwrite handle only binary data, so no problem with \n which might get transformed to \r\n in the output (on Windows and DOS) or \r (on (old) MACs)
Did you open the files in binary mode? What are you passing to
fopen
?