Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ alternative to OS.walk

I want to write a C++ program that reads a number of files from a directory, the number of files is indeterminate. I know of a Python implementation - OS.walk, that does this job perfectly :

Python OS.walk

Does anyone have any ideas of a C++ implementation of this OS.walk functionality?

Thanks in advance

like image 490
MattTheHack Avatar asked Feb 28 '13 17:02

MattTheHack


2 Answers

#include <boost/filesystem.hpp>
#include <iostream>

int main()
{
 boost::filesystem::path path = boost::filesystem::current_path();
 boost::filesystem::recursive_directory_iterator itr(path);
 while (itr != boost::filesystem::recursive_directory_iterator())
 {
   std::cout << itr->path().string() << std::endl;
   ++itr;
 }
}

Taken directly from http://www.deanwarrenuk.com/2012/09/how-to-recursively-walk-folder-in-c.html

Which offers a good explanation of why you need the boost library to hide the differences in file systems.

like image 109
hwatkins Avatar answered Nov 15 '22 16:11

hwatkins


With standard C++ this currently is impossible.

But you can use Boost.Filesystem (look for recursive_directory_iterator) which probably will included in future versions of C++.

like image 35
ipc Avatar answered Nov 15 '22 15:11

ipc