copying the contents of a binary file

2020-01-29 01:36发布

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?

4条回答
Emotional °昔
2楼-- · 2020-01-29 01:53

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.

查看更多
老娘就宠你
3楼-- · 2020-01-29 01:53

It's one of the most "popular" C gotchas.

查看更多
地球回转人心会变
4楼-- · 2020-01-29 01:56

You should use freadand 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'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)

查看更多
我只想做你的唯一
5楼-- · 2020-01-29 02:03

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

查看更多
登录 后发表回答