In trying to rework my logic in response to this question. I have decided to serialize protocol buffer objects using message-size + protobuf-object-after-SerializeToArray pairs,(don’t worry if you don’t get what I am talking about). Anyhow my implementation doesn’t work. So I decided to see how c++ fstream works. It’s a semantic nightmare, I can’t be sure if I need to use seekg to reposition the position handle after each read (or perhaps even after each write). I am only using write() and get() methods. The following contrived program is failing, why is it failing, and would I need seekg in this context ?
#include <fstream>
#include <boost/cstdint.hpp>
#include <iostream>
void write()
{
boost::uint8_t one = (boost::uint32_t )255;
boost::uint8_t two = (boost::uint32_t) 254;
boost::uint8_t three =(boost::uint32_t) 253;
std::fstream file("test", std::fstream::out | std::fstream::binary | std::fstream::trunc);
file.write( (char *) &one, sizeof(one));
file.write( (char *) &two, sizeof(two));
file.write( (char *) &three, sizeof(two));
std::cout << file.tellg() << std::endl;
file.flush();
file.close();
}
void read()
{
boost::uint8_t one=0;
boost::uint8_t two=0;
boost::uint8_t three=0;
std::fstream file("test", std::fstream::in | std::fstream::binary);
file.get((char *) & one, sizeof(one));
file.get((char *) & two, sizeof(two));
file.get((char *) & three, sizeof(three));
std::cout << file.tellg() << std::endl;
std::cout << (boost::uint32_t) one << ":" << (boost::uint32_t) two << ":" << (boost::uint32_t)three<< std::endl;
file.close();
}
int main()
{
write();
read();
}
The output is:
3
-1
0:0:0
C++ binary file io is making me feel sad and foolish 🙁
Instead of istream::get, you should use istream::read.
The former extracts characters until either (n – 1) characters have been extracted or the delimiting character is found. The later just reads unformated data from file.