Opening mode of Binary files
Hi I want to open a binary file for both reading and writing(without truncating, not appending). I use mode "r+b". I get no compiling errors but when read what I have written I get garbage values. Any idea.
But if I open the file for writing(mode as "wb")..write into in..close it and then open the file for reading(mode as "rb开发者_运维技巧") aand read from it ,then it works fine.
When you open a file in read/write modes such as "r+", "w+", you need to make sure your file pointer points to a valid position. fseek() is your friend here.
Also, as a good practice, remember to always check returned values from functions. In this case, maybe your fread() have failed without you noticing it.
When using buffered i/o you need to do a flush before reading back what you have written to ensure that none of the written data is still sat around in local buffers.
精彩评论