How to read a binary file in c? (video, images, or text)

前端 未结 3 1611
慢半拍i
慢半拍i 2020-12-05 16:35

I am trying to copy a file from a specified library to the current directory. I can copy text files perfectly. Any other files become corrupt. The program detects a feof bef

相关标签:
3条回答
  • 2020-12-05 16:53

    Are you on a Windows machine? Try adding "b" to the mode strings in the calls to fopen.

    From man fopen(3):

    The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-Unix environments.)
    0 讨论(0)
  • 2020-12-05 16:53

    You need to specify the "b" option to fopen:

    source = fopen("./library/rfc1350.txt", "rb");
    ...
    destination = fopen("rfc1350.txt", "wb");
    

    Without it, the file is opened in text ("t") mode, and this results in translation of end-of-line characters.

    0 讨论(0)
  • 2020-12-05 17:03

    You need to open the files in binary format rather than text format. In your calls to fopen, use "rb" and "wb" rather than "r" and "w" respectively.

    0 讨论(0)
提交回复
热议问题