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

How to read files in a directory? [closed]

asked 2021-05-06 15:29:30 -0600

anonymous user



I need to read some files from a directory and the std::filesystem does not seems to work. I already tried std::experimental::filesystem but I get the same error ‘std::filesystem’ has not been declared respectively ‘std::experimental::filesystem’ has not been declared. Is there any other way to read files?

std::vector<std::string> get_folder_content(std::string path)
    std::vector<std::string> files;
    std::filesystem::directory_iterator path_iterator(path);
    for (const auto& entry : path_iterator)
    return files;
edit retag flag offensive reopen merge delete

Closed for the following reason question is off-topic or not relevant. Please see for more details. by gvdhoorn
close date 2021-05-07 01:15:10.327633



I'm sorry to close your question, especially since it already has an answer, but this is not a ROS question. It's a general C++ question. Please keep your ROS Answers questions on topic, meaning: they should ask questions about ROS.

For all other questions (about programming, robotics, math, etc), try to find an appropriate forum, such as Stack Overflow, the Ubuntu fora, Robotics Stack Exchange, etc.

gvdhoorn gravatar image gvdhoorn  ( 2021-05-07 01:16:53 -0600 )edit

1 Answer

Sort by » oldest newest most voted

answered 2021-05-06 15:56:48 -0600

updated 2021-05-06 15:57:33 -0600

I found this c++ implementation of the glob function some time ago and have been using it since:

std::vector<std::string> glob(const std::string& pattern) {
using namespace std;

// glob struct resides on the stack glob_t glob_result;
memset(&glob_result, 0, sizeof(glob_result));

// do the glob operation int return_value = glob(pattern.c_str(), GLOB_TILDE, NULL, &glob_result); if (return_value != 0) { globfree(&glob_result); stringstream ss; ss << "glob() failed with return_value " << return_value << endl; throw std::runtime_error(ss.str()); }

// collect all the filenames into a std::list<std::string>
vector<string> filenames; for (size_t i = 0; i < glob_result.gl_pathc; ++i) { filenames.push_back(string(glob_result.gl_pathv[i])); } // cleanup
globfree(&glob_result); // done
return filenames; }

You can call this function as:

filenames = glob("<path>/*.<extension>");

edit flag offensive delete link more


Thanks I gonna try it out.

anonymous74063 gravatar image anonymous74063  ( 2021-05-06 16:22:11 -0600 )edit

Question Tools

1 follower


Asked: 2021-05-06 15:29:30 -0600

Seen: 879 times

Last updated: May 06 '21