Hello everybody.
i'm trying to read a binary file directly to a vector of uint8_t, but its not working. it gives me no error, just don't read anything.
heres's my code: first i create a vector with 100 elements, fill it with the number 40, and write it to the file. it works good, as i can see if i open the resulting file in a binary file viewer.
then, i re-fill the vector with the number 50. and try to read the binary file which contains only the number 40. but when i print the values of vec, it gives me the equivalent to 50.
The first thing I see wrong is that you fail to provide the correct open mode for your fstream(). You need to provide either the ::in or ::out flags along with the ::binary. With a fstream if you modify the second parameter it replaces the default open mode, it doesn't add to the default open mode.
Also since you're reusing the stream you really should also clear() any error flags. Just closing and opening a file doesn't always clear the stream errors.
thanks everyone, it's now working.
TheSmallGuy, i was really opening the file twice, which led to error.
jlb, i'm using binary files just because they are faster, and i need to read lots of things constantly (about ten times in a second).
and thanks for the working example, Thomas1965.
just one more thing: i tried change only from a specific point on. i thought i should use seekg, but it's doing nothing. lets say i have a 10-elements vector, and want to change 5 elements starting from the third one.
i use uint8_t just to avoid errors in case i'm reading this binary in another computer, since the size of int can vary. i'll probably change it to uint16_t later.
unfortunately your example does not work either. it seems seekg is doing nothing (?)
i use uint8_t just to avoid erros in case i'm reading this binary in another computer, since the size of int can vary.
But by sticking with a that type you're confusing yourself. By switching to an int (or int32_t) you can see that the values are changing.
unfortunately your example does not work either. it seems seekg is doing nothing (?)
What do you mean? Look closely at the second line of the output I supplied, it starts at 70, not 40 which means that the seek worked since 70 is the third element that you wrote to the file. Then you read 5 elements from the file starting at the third, 70,80,90,100, and 110, the rest of the numbers are the values that the vector contained.