I'm trying to record temporal state data.
This state data is sent from robot every 8ms.
So I want to record complete state data into a file(state.bin
).
I want to serialize writing/reading state data to/from a file. And I found that everything is fine with writing.
But when reading from a file, the file is likely to be read over end of file.
I tried while(!in.eof())
and while(in)
to check end of file.
But both failed.
How do I solve this problem?
Thanks.
Class for serialization
class RobotState
{
public:
RobotState()
{
}
void printState(std::ostream& stream)
{
//Intended for console output
}
double time;
int32_t mode;
double q[2];
std::string err_msg;
friend std::ostream& operator<<( std::ostream& stream, const RobotState& rs );
friend std::istream& operator>>( std::istream &stream, RobotState& rs );
};
Serialization/Deserialization
// write to the stream
std::ostream& operator<<( std::ostream &stream, const RobotState& rs )
{
stream.write((char*)&rs.time, sizeof(rs.time));
stream.write((char*)&rs.mode, sizeof(rs.mode));
stream.write((char*)rs.q, sizeof(rs.q[0])*2);
//serialize string
int32_t sz_err_msg = rs.err_msg.size();
stream.write((char*)&sz_err_msg, sizeof(sz_err_msg));
stream.write(rs.err_msg.c_str(), sz_err_msg);
return stream;
}
// read from the stream
std::istream& operator>>( std::istream &stream, RobotState& rs )
{
stream.read((char*)&rs.time, sizeof(rs.time));
stream.read((char*)&rs.mode, sizeof(rs.mode));
stream.read((char*)rs.q, sizeof(rs.q[0])*2);
int32_t sz_err_msg;
stream.read((char*)&sz_err_msg, sizeof(sz_err_msg));
char buffer[100];
stream.read(buffer, sz_err_msg);
buffer[sz_err_msg] = 0;
rs.err_msg = buffer;
return stream;
}
main code
int main(void)
{
RobotState rs_data;
/******************Serializing************************/
std::ofstream out;
out.open( "robotstate.bin",
std::ios::out | std::ios::trunc | std::ios::binary );
//Serialize data with contrived state data
out.close();
/******************Deserializing************************/
std::fstream in;
in.open("robotstate.bin", std::ios::in | std::ios::binary);
while(in)
{
in >> rs_data;
rs_data.printState(std::cout);
}
}