<p>How do you iterate through every file/directory recursively in standard C++?</p>

[{'answer_id': 67286, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 2, 'selected': False, 'text': '<p>You need to call OS-specific functions for filesystem traversal, like <code>open()</code> and <code>readdir()</code>. The C standard does not specify any filesystem-related functions.</p>\n'}, {'answer_id': 67307, 'author': '1800 INFORMATION', 'author_id': 3146, 'author_profile': 'https://Stackoverflow.com/users/3146', 'pm_score': 8, 'selected': True, 'text': '<p>In standard C++, technically there is no way to do this since standard C++ has no conception of directories. If you want to expand your net a little bit, you might like to look at using <a href="http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/index.htm" rel="noreferrer">Boost.FileSystem</a>. This has been accepted for inclusion in TR2, so this gives you the best chance of keeping your implementation as close as possible to the standard.</p>\n\n<p>An example, taken straight from the website:</p>\n\n<pre><code>bool find_file( const path &amp; dir_path,         // in this directory,\n                const std::string &amp; file_name, // search for this name,\n                path &amp; path_found )            // placing path here if found\n{\n  if ( !exists( dir_path ) ) return false;\n  directory_iterator end_itr; // default construction yields past-the-end\n  for ( directory_iterator itr( dir_path );\n        itr != end_itr;\n        ++itr )\n  {\n    if ( is_directory(itr-&gt;status()) )\n    {\n      if ( find_file( itr-&gt;path(), file_name, path_found ) ) return true;\n    }\n    else if ( itr-&gt;leaf() == file_name ) // see below\n    {\n      path_found = itr-&gt;path();\n      return true;\n    }\n  }\n  return false;\n}\n</code></pre>\n'}, {'answer_id': 67331, 'author': 'shoosh', 'author_id': 9611, 'author_profile': 'https://Stackoverflow.com/users/9611', 'pm_score': 2, 'selected': False, 'text': '<p>You don\'t. Standard C++ doesn\'t expose to concept of a directory. Specifically it doesn\'t give any way to list all the files in a directory.</p>\n\n<p>A horrible hack would be to use system() calls and to parse the results. The most reasonable solution would be to use some kind of cross-platform library such as <a href="https://en.wikipedia.org/wiki/Qt_%28software%29" rel="nofollow noreferrer">Qt</a> or even <a href="http://en.wikipedia.org/wiki/POSIX" rel="nofollow noreferrer">POSIX</a>.</p>\n'}, {'answer_id': 67336, 'author': 'Jorge Ferreira', 'author_id': 6508, 'author_profile': 'https://Stackoverflow.com/users/6508', 'pm_score': 6, 'selected': False, 'text': '<p>If using the Win32 API you can use the <strong>FindFirstFile</strong> and <strong>FindNextFile</strong> functions.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/aa365200(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa365200(VS.85).aspx</a></p>\n\n<p>For recursive traversal of directories you must inspect each <strong>WIN32_FIND_DATA.dwFileAttributes</strong> to check if the <strong>FILE_ATTRIBUTE_DIRECTORY</strong> bit is set. If the bit is set then you can recursively call the function with that directory. Alternatively you can use a stack for providing the same effect of a recursive call but avoiding stack overflow for very long path trees.</p>\n\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;stack&gt;\n#include &lt;iostream&gt;\n\nusing namespace std;\n\nbool ListFiles(wstring path, wstring mask, vector&lt;wstring&gt;&amp; files) {\n    HANDLE hFind = INVALID_HANDLE_VALUE;\n    WIN32_FIND_DATA ffd;\n    wstring spec;\n    stack&lt;wstring&gt; directories;\n\n    directories.push(path);\n    files.clear();\n\n    while (!directories.empty()) {\n        path = directories.top();\n        spec = path + L"\\\\" + mask;\n        directories.pop();\n\n        hFind = FindFirstFile(spec.c_str(), &amp;ffd);\n        if (hFind == INVALID_HANDLE_VALUE)  {\n            return false;\n        } \n\n        do {\n            if (wcscmp(ffd.cFileName, L".") != 0 &amp;&amp; \n                wcscmp(ffd.cFileName, L"..") != 0) {\n                if (ffd.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY) {\n                    directories.push(path + L"\\\\" + ffd.cFileName);\n                }\n                else {\n                    files.push_back(path + L"\\\\" + ffd.cFileName);\n                }\n            }\n        } while (FindNextFile(hFind, &amp;ffd) != 0);\n\n        if (GetLastError() != ERROR_NO_MORE_FILES) {\n            FindClose(hFind);\n            return false;\n        }\n\n        FindClose(hFind);\n        hFind = INVALID_HANDLE_VALUE;\n    }\n\n    return true;\n}\n\nint main(int argc, char* argv[])\n{\n    vector&lt;wstring&gt; files;\n\n    if (ListFiles(L"F:\\\\cvsrepos", L"*", files)) {\n        for (vector&lt;wstring&gt;::iterator it = files.begin(); \n             it != files.end(); \n             ++it) {\n            wcout &lt;&lt; it-&gt;c_str() &lt;&lt; endl;\n        }\n    }\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 67340, 'author': 'Matthew Scouten', 'author_id': 8508, 'author_profile': 'https://Stackoverflow.com/users/8508', 'pm_score': 3, 'selected': False, 'text': '<p>You don\'t. The C++ standard has no concept of directories. It is up to the implementation to turn a string into a file handle. The contents of that string and what it maps to is OS dependent. Keep in mind that C++ can be used to write that OS, so it gets used at a level where asking how to iterate through a directory is not yet defined (because you are writing the directory management code).</p>\n\n<p>Look at your OS API documentation for how to do this. If you need to be portable, you will have to have a bunch of <a href="https://en.wikipedia.org/wiki/C_preprocessor#Conditional_compilation" rel="nofollow noreferrer">#ifdef</a>s for various OSes.</p>\n'}, {'answer_id': 1471012, 'author': 'tonymontana', 'author_id': 396949, 'author_profile': 'https://Stackoverflow.com/users/396949', 'pm_score': 4, 'selected': False, 'text': '<p>In addition to the above mentioned boost::filesystem you may want to examine <a href="http://docs.wxwidgets.org/2.8/wx_wxdir.html" rel="noreferrer">wxWidgets::wxDir</a> and <a href="http://qt.nokia.com/doc/4.5/qdir.html" rel="noreferrer">Qt::QDir</a>.</p>\n\n<p>Both wxWidgets and Qt are open source, cross platform C++ frameworks.</p>\n\n<p><code>wxDir</code> provides a flexible way to traverse files recursively using <code>Traverse()</code> or a simpler <code>GetAllFiles()</code> function. As well you can implement the traversal with <code>GetFirst()</code> and <code>GetNext()</code> functions (I assume that Traverse() and GetAllFiles() are wrappers that eventually use GetFirst() and GetNext() functions).</p>\n\n<p><code>QDir</code> provides access to directory structures and their contents. There are several ways to traverse directories with QDir. You can iterate over the directory contents (including sub-directories) with QDirIterator that was instantiated with QDirIterator::Subdirectories flag. Another way is to use QDir\'s GetEntryList() function and implement a recursive traversal.</p>\n\n<p>Here is sample code (taken from <a href="http://www.digitalfanatics.org/projects/qt_tutorial/chapter08.html" rel="noreferrer">here</a> # Example 8-5) that shows how to iterate over all sub directories.</p>\n\n<pre><code>#include &lt;qapplication.h&gt;\n#include &lt;qdir.h&gt;\n#include &lt;iostream&gt;\n\nint main( int argc, char **argv )\n{\n    QApplication a( argc, argv );\n    QDir currentDir = QDir::current();\n\n    currentDir.setFilter( QDir::Dirs );\n    QStringList entries = currentDir.entryList();\n    for( QStringList::ConstIterator entry=entries.begin(); entry!=entries.end(); ++entry) \n    {\n         std::cout &lt;&lt; *entry &lt;&lt; std::endl;\n    }\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 12240511, 'author': 'Alex', 'author_id': 385489, 'author_profile': 'https://Stackoverflow.com/users/385489', 'pm_score': 5, 'selected': False, 'text': '<p>A fast solution is using C\'s <a href="http://en.wikipedia.org/wiki/Dirent.h">Dirent.h</a> library.</p>\n\n<p>Working code fragment from Wikipedia:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;dirent.h&gt;\n\nint listdir(const char *path) {\n    struct dirent *entry;\n    DIR *dp;\n\n    dp = opendir(path);\n    if (dp == NULL) {\n        perror("opendir: Path does not exist or could not be read.");\n        return -1;\n    }\n\n    while ((entry = readdir(dp)))\n        puts(entry-&gt;d_name);\n\n    closedir(dp);\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 19453043, 'author': 'Matthieu G', 'author_id': 759349, 'author_profile': 'https://Stackoverflow.com/users/759349', 'pm_score': 5, 'selected': False, 'text': '<p>You can make it even simpler with the new <a href="https://en.wikipedia.org/wiki/C++11" rel="noreferrer">C++11</a> range based <code>for</code> and <a href="http://en.wikipedia.org/wiki/Boost_%28C++_libraries%29" rel="noreferrer">Boost</a>:</p>\n\n<pre><code>#include &lt;boost/filesystem.hpp&gt;\n\nusing namespace boost::filesystem;    \nstruct recursive_directory_range\n{\n    typedef recursive_directory_iterator iterator;\n    recursive_directory_range(path p) : p_(p) {}\n\n    iterator begin() { return recursive_directory_iterator(p_); }\n    iterator end() { return recursive_directory_iterator(); }\n\n    path p_;\n};\n\nfor (auto it : recursive_directory_range(dir_path))\n{\n    std::cout &lt;&lt; it &lt;&lt; std::endl;\n}\n</code></pre>\n'}, {'answer_id': 19963262, 'author': 'leif', 'author_id': 679354, 'author_profile': 'https://Stackoverflow.com/users/679354', 'pm_score': 3, 'selected': False, 'text': '<p>You can use <a href="http://linux.die.net/man/3/ftw" rel="noreferrer"><code>ftw(3)</code> or <code>nftw(3)</code></a> to walk a filesystem hierarchy in C or C++ on <a href="http://en.wikipedia.org/wiki/POSIX" rel="noreferrer">POSIX</a> systems.</p>\n'}, {'answer_id': 23475480, 'author': 'DikobrAz', 'author_id': 1008902, 'author_profile': 'https://Stackoverflow.com/users/1008902', 'pm_score': 3, 'selected': False, 'text': '<p>Boost::filesystem provides recursive_directory_iterator, which is quite convenient for this task:</p>\n\n<pre><code>#include "boost/filesystem.hpp"\n#include &lt;iostream&gt;\n\nusing namespace boost::filesystem;\n\nrecursive_directory_iterator end;\nfor (recursive_directory_iterator it("./"); it != end; ++it) {\n    std::cout &lt;&lt; *it &lt;&lt; std::endl;                                    \n}\n</code></pre>\n'}, {'answer_id': 23713140, 'author': 'Ibrahim', 'author_id': 1959246, 'author_profile': 'https://Stackoverflow.com/users/1959246', 'pm_score': 1, 'selected': False, 'text': '<p>If you are on Windows, you can use the FindFirstFile together with FindNextFile API. You can use FindFileData.dwFileAttributes to check if a given path is a file or a directory. If it\'s a directory, you can recursively repeat the algorithm.</p>\n\n<p>Here, I have put together some code that lists all the files on a Windows machine.</p>\n\n<p><a href="http://dreams-soft.com/projects/traverse-directory" rel="nofollow">http://dreams-soft.com/projects/traverse-directory</a></p>\n'}, {'answer_id': 32889434, 'author': 'Adi Shavit', 'author_id': 135862, 'author_profile': 'https://Stackoverflow.com/users/135862', 'pm_score': 7, 'selected': False, 'text': '<p>From C++17 onward, the <a href="https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator" rel="noreferrer"><code>&lt;filesystem&gt;</code></a> header, and range-<code>for</code>, you can simply do this:</p>\n<pre><code>#include &lt;filesystem&gt;\n\nusing recursive_directory_iterator = std::filesystem::recursive_directory_iterator;\n...\nfor (const auto&amp; dirEntry : recursive_directory_iterator(myPath))\n     std::cout &lt;&lt; dirEntry &lt;&lt; std::endl;\n</code></pre>\n<p>As of C++17, <code>std::filesystem</code> is part of the standard library and can be found in the <code>&lt;filesystem&gt;</code> header (no longer &quot;experimental&quot;).</p>\n'}, {'answer_id': 42866915, 'author': 'ndrewxie', 'author_id': 7077165, 'author_profile': 'https://Stackoverflow.com/users/7077165', 'pm_score': 3, 'selected': False, 'text': '<p>You would probably be best with either boost or c++14\'s experimental filesystem stuff. <strong>IF</strong> you are parsing an internal directory (ie. used for your program to store data after the program was closed), then make an index file that has an index of the file contents. By the way, you probably would need to use boost in the future, so if you don\'t have it installed, install it! Second of all, you could use a conditional compilation, e.g.:</p>\n\n<pre><code>#ifdef WINDOWS //define WINDOWS in your code to compile for windows\n#endif\n</code></pre>\n\n<p>The code for each case is taken from <a href="https://stackoverflow.com/a/67336/7077165">https://stackoverflow.com/a/67336/7077165</a></p>\n\n<pre><code>#ifdef POSIX //unix, linux, etc.\n#include &lt;stdio.h&gt;\n#include &lt;dirent.h&gt;\n\nint listdir(const char *path) {\n    struct dirent *entry;\n    DIR *dp;\n\n    dp = opendir(path);\n    if (dp == NULL) {\n        perror("opendir: Path does not exist or could not be read.");\n        return -1;\n    }\n\n    while ((entry = readdir(dp)))\n        puts(entry-&gt;d_name);\n\n    closedir(dp);\n    return 0;\n}\n#endif\n#ifdef WINDOWS\n#include &lt;windows.h&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;stack&gt;\n#include &lt;iostream&gt;\n\nusing namespace std;\n\nbool ListFiles(wstring path, wstring mask, vector&lt;wstring&gt;&amp; files) {\n    HANDLE hFind = INVALID_HANDLE_VALUE;\n    WIN32_FIND_DATA ffd;\n    wstring spec;\n    stack&lt;wstring&gt; directories;\n\n    directories.push(path);\n    files.clear();\n\n    while (!directories.empty()) {\n        path = directories.top();\n        spec = path + L"\\\\" + mask;\n        directories.pop();\n\n        hFind = FindFirstFile(spec.c_str(), &amp;ffd);\n        if (hFind == INVALID_HANDLE_VALUE)  {\n            return false;\n        } \n\n        do {\n            if (wcscmp(ffd.cFileName, L".") != 0 &amp;&amp; \n                wcscmp(ffd.cFileName, L"..") != 0) {\n                if (ffd.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY) {\n                    directories.push(path + L"\\\\" + ffd.cFileName);\n                }\n                else {\n                    files.push_back(path + L"\\\\" + ffd.cFileName);\n                }\n            }\n        } while (FindNextFile(hFind, &amp;ffd) != 0);\n\n        if (GetLastError() != ERROR_NO_MORE_FILES) {\n            FindClose(hFind);\n            return false;\n        }\n\n        FindClose(hFind);\n        hFind = INVALID_HANDLE_VALUE;\n    }\n\n    return true;\n}\n#endif\n//so on and so forth.\n</code></pre>\n'}, {'answer_id': 56376599, 'author': 'abhiarora', 'author_id': 5735010, 'author_profile': 'https://Stackoverflow.com/users/5735010', 'pm_score': 3, 'selected': False, 'text': '<p>We are in 2019. We have <a href="https://en.cppreference.com/w/cpp/filesystem" rel="noreferrer">filesystem</a> standard library in <code>C++</code>. The <code>Filesystem library</code> provides facilities for performing operations on file systems and their components, such as paths, regular files, and directories.</p>\n\n<p>There is an important note on <a href="https://en.cppreference.com/w/cpp/filesystem" rel="noreferrer">this link</a> if you are considering portability issues. It says:</p>\n\n<blockquote>\n  <p>The filesystem library facilities may be unavailable if a hierarchical file system is not accessible to the implementation, or if it does not provide the necessary capabilities. Some features may not be available if they are not supported by the underlying file system (e.g. the FAT filesystem lacks symbolic links and forbids multiple hardlinks). In those cases, errors must be reported.</p>\n</blockquote>\n\n<p>The filesystem library was originally developed as <code>boost.filesystem</code>, was published as the technical specification ISO/IEC TS 18822:2015, and finally merged to ISO C++ as of C++17. The boost implementation is currently available on more compilers and platforms than the C++17 library.</p>\n\n<p><strong>@adi-shavit has answered this question when it was part of std::experimental and he has updated this answer in 2017. I want to give more details about the library and show more detailed example.</strong></p>\n\n<p><a href="https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator" rel="noreferrer">std::filesystem::recursive_directory_iterator</a> is an <code>LegacyInputIterator</code> that iterates over the directory_entry elements of a directory, and, recursively, over the entries of all subdirectories. The iteration order is unspecified, except that each directory entry is visited only once.</p>\n\n<p>If you don\'t want to recursively iterate over the entries of subdirectories, then <a href="https://en.cppreference.com/w/cpp/filesystem/directory_iterator" rel="noreferrer">directory_iterator</a> should be used.</p>\n\n<p>Both iterators returns an object of <a href="https://en.cppreference.com/w/cpp/filesystem/directory_entry" rel="noreferrer">directory_entry</a>. <code>directory_entry</code> has various useful member functions like <code>is_regular_file</code>, <code>is_directory</code>, <code>is_socket</code>, <code>is_symlink</code> etc. The <code>path()</code> member function returns an object of <a href="https://en.cppreference.com/w/cpp/filesystem/path" rel="noreferrer">std::filesystem::path</a> and it can be used to get <code>file extension</code>, <code>filename</code>, <code>root name</code>.</p>\n\n<p>Consider the example below. I have been using <code>Ubuntu</code> and compiled it over the terminal using </p>\n\n<p><strong>g++ example.cpp --std=c++17 -lstdc++fs -Wall</strong> </p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;filesystem&gt;\n\nvoid listFiles(std::string path)\n{\n    for (auto&amp; dirEntry: std::filesystem::recursive_directory_iterator(path)) {\n        if (!dirEntry.is_regular_file()) {\n            std::cout &lt;&lt; "Directory: " &lt;&lt; dirEntry.path() &lt;&lt; std::endl;\n            continue;\n        }\n        std::filesystem::path file = dirEntry.path();\n        std::cout &lt;&lt; "Filename: " &lt;&lt; file.filename() &lt;&lt; " extension: " &lt;&lt; file.extension() &lt;&lt; std::endl;\n\n    }\n}\n\nint main()\n{\n    listFiles("./");\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 62057783, 'author': 'pooya13', 'author_id': 3847255, 'author_profile': 'https://Stackoverflow.com/users/3847255', 'pm_score': 4, 'selected': False, 'text': '<p>You can use <code>std::filesystem::recursive_directory_iterator</code>. But beware, this includes symbolic (soft) links. If you want to avoid them you can use <code>is_symlink</code>. Example usage:</p>\n<pre><code>size_t directory_size(const std::filesystem::path&amp; directory)\n{\n    size_t size{ 0 };\n    for (const auto&amp; entry : std::filesystem::recursive_directory_iterator(directory))\n    {\n        if (entry.is_regular_file() &amp;&amp; !entry.is_symlink())\n        {\n            size += entry.file_size();\n        }\n    }\n    return size;\n}\n</code></pre>\n'}, {'answer_id': 63006457, 'author': 'Milind Deore', 'author_id': 3994228, 'author_profile': 'https://Stackoverflow.com/users/3994228', 'pm_score': 0, 'selected': False, 'text': '<p>File tree walk <code>ftw</code> is a recursive way to wall the whole directory tree in the path. More details are <a href="https://linux.die.net/man/3/ftw" rel="nofollow noreferrer">here</a>.</p>\n<p>NOTE : You can also use <code>fts</code> that can skip hidden files like <code>.</code> or <code>..</code> or <code>.bashrc</code></p>\n<pre><code>#include &lt;ftw.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;sys/stat.h&gt;\n#include &lt;string.h&gt;\n\n \nint list(const char *name, const struct stat *status, int type)\n{\n     if (type == FTW_NS)\n     {\n         return 0;\n     }\n\n     if (type == FTW_F)\n     {\n         printf(&quot;0%3o\\t%s\\n&quot;, status-&gt;st_mode&amp;0777, name);\n     }\n\n     if (type == FTW_D &amp;&amp; strcmp(&quot;.&quot;, name) != 0)\n     {\n         printf(&quot;0%3o\\t%s/\\n&quot;, status-&gt;st_mode&amp;0777, name);\n     }\n     return 0;\n}\n\nint main(int argc, char *argv[])\n{\n     if(argc == 1)\n     {\n         ftw(&quot;.&quot;, list, 1);\n     }\n     else\n     {\n         ftw(argv[1], list, 1);\n     }\n\n     return 0;\n}\n</code></pre>\n<p>output looks like following:</p>\n<pre><code>0755    ./Shivaji/\n0644    ./Shivaji/20200516_204454.png\n0644    ./Shivaji/20200527_160408.png\n0644    ./Shivaji/20200527_160352.png\n0644    ./Shivaji/20200520_174754.png\n0644    ./Shivaji/20200520_180103.png\n0755    ./Saif/\n0644    ./Saif/Snapchat-1751229005.jpg\n0644    ./Saif/Snapchat-1356123194.jpg\n0644    ./Saif/Snapchat-613911286.jpg\n0644    ./Saif/Snapchat-107742096.jpg\n0755    ./Milind/\n0644    ./Milind/IMG_1828.JPG\n0644    ./Milind/IMG_1839.JPG\n0644    ./Milind/IMG_1825.JPG\n0644    ./Milind/IMG_1831.JPG\n0644    ./Milind/IMG_1840.JPG\n</code></pre>\n<p>Let us say if you want to match a filename (example: searching for all the <code>*.jpg, *.jpeg, *.png</code> files.) for a specific needs, use <code>fnmatch</code>.</p>\n<pre><code> #include &lt;ftw.h&gt;\n #include &lt;stdio.h&gt;\n #include &lt;sys/stat.h&gt;\n #include &lt;iostream&gt;\n #include &lt;fnmatch.h&gt;\n\n static const char *filters[] = {\n     &quot;*.jpg&quot;, &quot;*.jpeg&quot;, &quot;*.png&quot;\n };\n\n int list(const char *name, const struct stat *status, int type)\n {\n     if (type == FTW_NS)\n     {\n         return 0;\n     }\n\n     if (type == FTW_F)\n     {\n         int i;\n         for (i = 0; i &lt; sizeof(filters) / sizeof(filters[0]); i++) {\n             /* if the filename matches the filter, */\n             if (fnmatch(filters[i], name, FNM_CASEFOLD) == 0) {\n                 printf(&quot;0%3o\\t%s\\n&quot;, status-&gt;st_mode&amp;0777, name);\n                 break;\n             }\n         }\n     }\n\n     if (type == FTW_D &amp;&amp; strcmp(&quot;.&quot;, name) != 0)\n     {\n         //printf(&quot;0%3o\\t%s/\\n&quot;, status-&gt;st_mode&amp;0777, name);\n     }\n     return 0;\n }\n\n int main(int argc, char *argv[])\n {\n     if(argc == 1)\n     {\n         ftw(&quot;.&quot;, list, 1);\n     }\n     else\n     {\n         ftw(argv[1], list, 1);\n     }\n\n     return 0;\n }\n</code></pre>\n'}, {'answer_id': 64443732, 'author': 'Bensuperpc', 'author_id': 10152334, 'author_profile': 'https://Stackoverflow.com/users/10152334', 'pm_score': 2, 'selected': False, 'text': '<p>On C++17 you can by this way :</p>\n<pre><code>#include &lt;filesystem&gt;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\nnamespace fs = std::filesystem;\n\nint main()\n{\n    std::ios_base::sync_with_stdio(false);\n    for (const auto &amp;entry : fs::recursive_directory_iterator(&quot;.&quot;)) {\n        if (entry.path().extension() == &quot;.png&quot;) {\n            std::cout &lt;&lt; entry.path().string() &lt;&lt; std::endl;\n            \n        }\n    }\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 65090772, 'author': 'Hu Xixi', 'author_id': 7121726, 'author_profile': 'https://Stackoverflow.com/users/7121726', 'pm_score': 0, 'selected': False, 'text': '<p>Answers of getting all file names recursively with C++11 for Windows and Linux(with <code>experimental/filesystem</code>):<br />\nFor Windows:</p>\n<pre class="lang-cpp prettyprint-override"><code>#include &lt;io.h&gt;\n#include &lt;sys/types.h&gt;\n#include &lt;sys/stat.h&gt;\n#include &lt;windows.h&gt;\nvoid getFiles_w(string path, vector&lt;string&gt;&amp; files) {\n    intptr_t hFile = 0; \n    struct _finddata_t fileinfo;  \n    string p; \n    if ((hFile = _findfirst(p.assign(path).append(&quot;\\\\*&quot;).c_str(), &amp;fileinfo)) != -1) {\n        do {\n            if ((fileinfo.attrib &amp; _A_SUBDIR)) {\n                if (strcmp(fileinfo.name, &quot;.&quot;) != 0 &amp;&amp; strcmp(fileinfo.name, &quot;..&quot;) != 0)\n                    getFiles(p.assign(path).append(&quot;/&quot;).append(fileinfo.name), files);\n            }\n            else {\n                files.push_back(p.assign(path).append(&quot;/&quot;).append(fileinfo.name));\n            }\n        } while (_findnext(hFile, &amp;fileinfo) == 0);\n    }\n}\n</code></pre>\n<p>For Linux:</p>\n<pre class="lang-cpp prettyprint-override"><code>#include &lt;experimental/filesystem&gt;\nbool getFiles(std::experimental::filesystem::path path, vector&lt;string&gt;&amp; filenames) {\n    namespace stdfs = std::experimental::filesystem;\n    // http://en.cppreference.com/w/cpp/experimental/fs/directory_iterator\n    const stdfs::directory_iterator end{} ;\n    \n    for (stdfs::directory_iterator iter{path}; iter != end ; ++iter) {\n        // http://en.cppreference.com/w/cpp/experimental/fs/is_regular_file \n        if (!stdfs::is_regular_file(*iter)) { // comment out if all names (names of directories tc.) are required \n            if (getFiles(iter-&gt;path(), filenames)) \n                return true;\n        }\n        else {\n            filenames.push_back(iter-&gt;path().string()) ;\n            cout &lt;&lt; iter-&gt;path().string() &lt;&lt; endl;  \n        }\n    }\n    return false;\n}\n</code></pre>\n<p>Just remember to link <code>-lstdc++fs</code> when you compile it with <code>g++</code> in Linux.</p>\n'}, {'answer_id': 66687906, 'author': 'Mou', 'author_id': 4292371, 'author_profile': 'https://Stackoverflow.com/users/4292371', 'pm_score': 0, 'selected': False, 'text': '<p>Employee Visual C++ and WIN API:</p>\n<pre><code>bool Parser::queryDIR(string dir_name) {\n    vector&lt;string&gt; sameLayerFiles;\n    bool ret = false;\n    string dir = &quot;&quot;;\n    //employee wide char\n    dir = dir_name  + &quot;\\\\*.*&quot;;;\n    //employee WIN File API\n    WIN32_FIND_DATA  fd;\n    WIN32_FIND_DATA  fd_dir;\n    HANDLE hFind = ::FindFirstFile(getWC(dir.c_str()), &amp;fd);\n    HANDLE hFind_dir = ::FindFirstFile(getWC(dir.c_str()), &amp;fd_dir);\n    string str_subdir;\n    string str_tmp;\n    //recursive call for diving into sub-directories\n    do {\n        if ((fd_dir.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY) ) {\n            //ignore trival file node\n            while(true) {\n                FindNextFile(hFind_dir, &amp;fd_dir);\n                str_tmp = wc2str(fd_dir.cFileName);\n                if (str_tmp.compare(&quot;.&quot;) &amp;&amp; str_tmp.compare(&quot;..&quot;)){\n                    break;\n                }\n            }\n            if ((fd_dir.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY) ) {\n                str_subdir = wc2str(fd_dir.cFileName);\n                ret = queryDIR(dir_name + &quot;\\\\&quot; + str_subdir);\n            }\n        }\n    } while(::FindNextFile(hFind_dir, &amp;fd_dir));\n\n    //iterate same layer files\n    do { \n        if (!(fd.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY)) {\n            str_tmp = wc2str(fd.cFileName);\n            string fname = dir_name + &quot;\\\\&quot; + str_tmp;\n            sameLayerFiles.push_back(fname);\n        }\n    } while(::FindNextFile(hFind, &amp;fd));    \n\n    for (std::vector&lt;string&gt;::iterator it=sameLayerFiles.begin(); it!=sameLayerFiles.end(); it++) {\n        std::cout &lt;&lt; &quot;iterated file:&quot; &lt;&lt; *it &lt;&lt; &quot;...&quot; &lt;&lt; std::endl;\n        //Doing something with every file here\n    }\n    return true;   \n}\n</code></pre>\n<p>Hope my code can help :)</p>\n<p>And you can see more details and program screen-shots on <a href="https://github.com/MouChiaHung/Grep" rel="nofollow noreferrer">My GitHub</a></p>\n'}]
['https://Stackoverflow.com/questions/67273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10184/']