Ask Your Question

Read text file to build a vector.

asked 2014-07-29 18:13:49 -0500

AsifA gravatar image

Hi, I am trying to read a text file "filename.txt" to build a vector of doubles. I used following code which works fine when I am using outside ROS. However, when I include this code as a part of my .cpp file in a ROS package, it does not work. At line while(myFile >> value), it does not read any thing and hence does not enter the loop. Any help is appreciated.

#include <fstream>
#include <vector>
#include <iostream>

std::vector<double> vec;

void readDATA(){
double value;
std::ifstream myFile;"filename.txt", std::ios::app); 
if (myFile.is_open()){
    std::cout << "File is open."<<std::endl;
    while(myFile >> value){
        std::cout << "value is " <<value<< std::endl;
else std::cout << "Unable to open the file"; 

int main(){
return 0;
edit retag flag offensive close merge delete



"filename.txt" is relative to you current directory. If the file is relative to an ROS package, you can use #include <ros package.h=""> and ros::package::getPath("some_package")

kmhallen gravatar image kmhallen  ( 2014-07-29 19:15:56 -0500 )edit

Thanks kmhallen, I replaced line number 10 with following code:"package_name")+"/filename.txt"), std::ios::app); and included the header file as #include <ros package.h="">. Still getting "no matching function" error. Any idea please?

AsifA gravatar image AsifA  ( 2014-07-30 16:24:33 -0500 )edit

PS: The error is: error: no matching function for call to ‘std::basic_ifstream<char>::open(std::basic_string<char>, const openmode&)’

AsifA gravatar image AsifA  ( 2014-07-30 16:28:12 -0500 )edit

1 Answer

Sort by » oldest newest most voted

answered 2014-07-29 20:20:28 -0500

Mehdi. gravatar image

Try putting the full path to your file. Normally it should work. If you don't want to put the full path, you can either do as kmhallen commented or move to your package's folder before executing rosrun

roscd your_package
rosrun your_node

If filename.txt is in your package's folder of course.

edit flag offensive delete link more


Thanks Mehdi, that was helpful.

AsifA gravatar image AsifA  ( 2014-07-30 16:29:25 -0500 )edit

Your Answer

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

Add Answer

Question Tools



Asked: 2014-07-29 18:13:49 -0500

Seen: 3,387 times

Last updated: Jul 29 '14