Question 12.38

How can I read a binary data file properly? I'm occasionally seeing 0x0a and 0x0d values getting garbled, and it seems 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".

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. See also question 20.5.

References: ANSI Sec. 4.9.5.3
ISO Sec. 7.9.5.3
H&S Sec. 15.2.1 p. 348


Read sequentially: prev next up top


This page by Steve Summit // Copyright 1995 // mail feedback