Basic and Advance C Question:
How can I read a binary data file properly?
Answer:
How can I read a binary data file properly? I'm occasionally seeing 0x0a and 0x0d values getting garbled, and I seem to hit EOF prematurely if the data contains the value 0x1a.
When you're reading a binary data file, you should specify "rb" mode when calling fopen, to make sure that text file translations do not occur. Similarly, when writing binary data files, use "wb". (Under operating systems such as Unix which don't distinguish between text and binary files, "b" may not be required, but is harmless.)
Note that the text/binary distinction is made when you open the file: once a file is open, it doesn't matter which I/O calls you use on it.
When you're reading a binary data file, you should specify "rb" mode when calling fopen, to make sure that text file translations do not occur. Similarly, when writing binary data files, use "wb". (Under operating systems such as Unix which don't distinguish between text and binary files, "b" may not be required, but is harmless.)
Note that the text/binary distinction is made when you open the file: once a file is open, it doesn't matter which I/O calls you use on it.
Previous Question | Next Question |
What is the difference between text and binary I/O? | How can I get back to the interactive keyboard if stdin is redirected? |