Ask Your Question
2

How to read and writing ROS message efficient into files c++

asked 2014-02-12 21:46:12 -0500

Markus Bader gravatar image

updated 2016-10-24 08:35:52 -0500

ngrennan gravatar image

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();
    }
    ....
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2014-02-12 22:50:48 -0500

ahendrix gravatar image

rosbag has a C++ API for reading and writing bag files: http://wiki.ros.org/rosbag/Code%20API

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2014-02-12 21:46:12 -0500

Seen: 2,066 times

Last updated: Feb 12 '14