How to iterate all dirs and files in a dir in C++?

Posted on In Programming, QA, Tutorial

How to iterate all dirs and files in a dir in C++?

To open a dir, we can use opendir() to open a directory stream.

DIR *opendir(const char *name);

Then we can use readdir() to iterate the directory stream.

struct dirent *readdir(DIR *dirp);

Here is an example C++ program using these 2 library functions.

#include <cstdio>

#include <dirent.h>

#include <iostream>
#include <string>

int ListDir(const std::string& path) {
  struct dirent *entry;
  DIR *dp;

  dp = ::opendir(path.c_str());
  if (dp == NULL) {
    perror("opendir: Path does not exist or could not be read.");
    return -1;

  while ((entry = ::readdir(dp))) {
    std::cout << entry->d_name << std::endl;

  return 0;

int main (int argc, char *argv[]) {
  if (argc < 2) {
    std::cerr << "Usage: " << argv[0] << " path\n";
    return 1;
  std::string input(argv[1]);

  return ListDir(input);

Execution example is as follows.

$ ./build/main .

If recursive visiting all sub directories is needed, the ListDir() function can be called recursively for directories from the directory stream.

Leave a Reply

Your email address will not be published. Required fields are marked *