Copying the contents of a binary file
I am developing an image decoder and as a first step I tried to just copy using c. Open the file and write its contents to a new file. Below is the code 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 runs without any errors, but the image file (".mpmp") is not copied correctly. I noticed that the size of the copied file is smaller and only 20% of the image is visible, everything else is black. When I tried using simple text files, the copy was complete.
Do you know what the problem is?
a source to share
Make sure the type of the variable c
is equal int
, not char
. In other words, write more code.
This is because the value of the constant is EOF
usually -1, and if you read characters as char
-sized values, every byte that is equal 0xff
will look like an EOF constant. With extra bits int
; there is room to separate the two.
a source to share
You must use fread
and fwrite
using a block at a time
FILE *fd1 = fopen("source.bmp", "r");
FILE *fd2 = fopen("destination.bmp", "w");
if(!fd1 || !fd2)
// handle open error
size_t l1;
unsigned char buffer[8192];
//Data to be read
while((l1 = fread(buffer, 1, sizeof buffer, fd1)) > 0) {
size_t l2 = fwrite(buffer, 1, l1, fd2);
if(l2 < l1) {
if(ferror(fd2))
// handle error
else
// Handle media full
}
}
fclose(fd1);
fclose(fd2);
It reads significantly faster in large blocks, and fread / fwrite only handles binary data, so no problem with \ n that can be converted to \ r \ n on output (on Windows and DOS) or \ r (on (old) MAC )
a source to share