How to read and writing ROS message efficient into files c++
Hi!
With the following code I am able to read and write ros message into binary files using c++. But I have to create first memory buffer to use the ros ros::serialization::OStream or ros::serialization::IStream is there a way how to stream messages directly into files similar to a std::ofstream?
void LaserLineFilterNode::callback (const sensor_msgs::LaserScan::ConstPtr& _msg) {
{
// Write to File
std::ofstream ofs("/tmp/filename.txt", std::ios::out|std::ios::binary);
uint32_t serial_size = ros::serialization::serializationLength(*_msg);
boost::shared_array<uint8_t> obuffer(new uint8_t[serial_size]); // This i like to avoid
ros::serialization::OStream ostream(obuffer.get(), serial_size); // This i like to avoid
ros::serialization::serialize(ostream, *_msg); // I would like to use the ofstream here?
ofs.write((char*) obuffer.get(), serial_size); // This i like to avoid
ofs.close();
}
{
// Read from File to msg_scan_
//sensor_msgs::LaserScan msg_scan_ --> is a class variable
std::ifstream ifs("/tmp/filename.txt", std::ios::in|std::ios::binary);
ifs.seekg (0, std::ios::end);
std::streampos end = ifs.tellg();
ifs.seekg (0, std::ios::beg);
std::streampos begin = ifs.tellg();
uint32_t file_size = end-begin;
boost::shared_array<uint8_t> ibuffer(new uint8_t[file_size]); // This i like to avoid
ifs.read((char*) ibuffer.get(), file_size); // This i like to avoid
ros::serialization::IStream istream(ibuffer.get(), file_size); // I would like to use the ifstream here?
ros::serialization::deserialize(istream, msg_scan_); // This i like to avoid
ifs.close();
}
....