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 :(
boost::uint8_tisunsigned char. To output the value onstd::cout, you should cast it toint(or any other non-char integer type).feff 00fd(keep in mind endianess :), so the writing part seems to be working, at least.cout, and checkfstreamstate after all usages in thereadcode.