copying the contents of a binary file

筅森魡賤 提交于 2019-11-27 09:22:30

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.

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

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

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!