ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

read information from a file

asked 2014-06-06 06:38:41 -0600

nat gravatar image

Hi, i want to read information from a .txt file and then use it in a ros node. thanks

edit retag flag offensive close merge delete

2 Answers

Sort by » oldest newest most voted
1

answered 2014-06-06 06:56:29 -0600

Jérôme gravatar image

updated 2014-06-06 10:02:17 -0600

Why not just use the C++ api to read file ?


#include <fstream>
#include <streambuf>
#include <string>
#include <cerrno>

std::string get_file_contents(const char *filename)
{
  std::ifstream in(filename, std::ios::in | std::ios::binary);
  if (in)
  {
    return(std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()));
  }
  throw(errno);
}

Check if your file exist, of course it depends also of the content of the file. With a data file like that :

0 1 2 3 4 5 6 7 8

It's works with this piece of code :

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

int main()
{
  std::ifstream file("test.txt");
  std::vector<int> data;

  int a[3][3];

  std::memset(a, 0, sizeof(a[0][0]) * 3 * 3);

  if(file.is_open())
  {
    for(int i=0;i<3 && file.good() ;i++)
    {
      for(int j=0;j<3 && file.good() ;j++)
      {
        file >> a[i][j];
      }
    }
  }
  else std::cerr<<"File not found !"<<std::endl;

  for(int i=0;i<3;i++)
    for(int j=0;j<3;j++)
      std::cout<<a[i][j]<<" ";

  return 0;
}
edit flag offensive delete link more

Comments

thanks . In fact I have tried with the following code: ifstream label1("File_name"); for(int i=0; i<r; i++)="" {="" for(int="" j="0;" j<c;="" j++)="" {="" label1="">> a[i][j]; } } however, only appear 0 in the array a.

nat gravatar image nat  ( 2014-06-06 09:29:11 -0600 )edit
0

answered 2014-06-06 09:39:43 -0600

nat gravatar image

In fact I have tried with the following code:

ifstream label1("File_name");

for ( int i=0; i<r ;="" i++="" )="" {="" for(int="" j="0;" j<c;="" j++)="" {="" label1="">> a[i][j];

}

}

however, only appear 0 in the array a.

edit flag offensive delete link more

Question Tools

Stats

Asked: 2014-06-06 06:38:41 -0600

Seen: 1,759 times

Last updated: Jun 06 '14