Write data from topic to text file in C++ in ros node
I am trying to write poses to text file, the code is :
#include <ros/ros.h>
#include <nav_msgs/Odometry.h>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <stdio.h>
std::ofstream ofs ("home/basma/catkin_ws/poses.txt",std::ofstream::app);
void callhandler(const nav_msgs::Odometry::ConstPtr& msg)
{ if (ofs.is_open())
//store array contents to text file
ofs <<msg.pose.pose.x<<"\n";
else printf("Unable to open file \n");
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "main");
ros::NodeHandle nh;
ros::Subscriber Listener = nh.subscribe<nav_msgs::Odometry>("/odom", 100, callhandler);
ros::spin();
return 0;
}
But when use catkin_make
the following error occure:
/home/basma/catkin_ws/src/poses_to_fileC/src/poses_to_fileC.cpp: In function ‘void callhandler(const ConstPtr&)’:
/home/basma/catkin_ws/src/poses_to_fileC/src/poses_to_fileC.cpp:15:22: error: ‘const ConstPtr’ {aka ‘const class boost::shared_ptr<const nav_msgs::Odometry_<std::allocator<void> > >’} has no member named ‘pose’
Could anyone help me? 15 | ofs <<msg.pose.pose.x<<"\n";
Asked by Basma on 2022-08-28 03:18:06 UTC
Answers
The build error is caused by the fact that msg
is a pointer. You must dereference it using the ->
operator.
Asked by BlakeAnderson on 2022-08-28 16:38:56 UTC
Comments
Do you mean update the declaration as:
void callhandler(const nav_msgs::Odometry::ConstPtr-> msg)
Asked by Basma on 2022-08-29 03:57:02 UTC
You need to do: msg->pose.pose.x
. This is called "dereferencing" the pointer.
I strongly recommend familiarizing yourself with C++ pointers: https://cplusplus.com/doc/tutorial/pointers/
Asked by BlakeAnderson on 2022-08-29 09:49:03 UTC
The problem has been sloved:
I was wrongly running the node as : rosrun pkg_name nodefile.cpp
But the correct way is running as :rosrun pkg_name nodefile
Asked by Basma on 2022-09-07 05:26:06 UTC
Comments