Listing all files and sub-directories within a directory in C++

In this tutorial, we are going to learn how to get all the contents i.e., names of files and sub-directories within a given directory. And we are going to implement it using C++.

Implementation in C++

# include <iostream>
# include <dirent.h>
using namespace std;

void directory_contents ( char * directory_path )
  DIR *dh;
  struct dirent * contents; 
  dh = opendir ( directory_path );
  if ( !dh )
    cout << "The given directory is not found";

  while ( ( contents = readdir ( dh ) ) != NULL )
    string name = contents->d_name;
    cout << name << endl;

  closedir ( dh );

int main ()
  directory_contents ( (char*) "C:\\Users\\hello\\Downloads" );
  return 0;

The output is a list of files and sub-directories present within the specified directory. This output varies from system to system. Here, the list of files and sub-directories present within the Downloads directory of my system is displayed. Because Downloads is the directory I specified.


Dev-Cpp 5.11 TDM-GCC 4.9.2 Setup.exe

Explanation of the code listing all files and sub-directories

We need to include the dirent.h header file. It contains the necessary constructs for handling directories. It contains prototypes of opendir(), closedir(), etc.

Let us write a method named directory_contents. This method lists all the contents of the given directory.

Create a pointer of type DIR for handling directories. The entries in a directory are of structure dirent type. So, we created a pointer of type struct dirent to handle the directory entries.

Follow 3 steps to perform any operation on directories. They are:

  1. Open the directory: this is done using the opendir() method. If the directory is not present, then the opendir() method returns a NULL pointer.
  2. Perform the operation
  3. Close the directory: this is done using the closedir() method.

Use the readdir() method to read the contents of the directory. When readdir() is executed, a pointer is created to the first entry. Next time the readdir() is executed the pointer is incremented.

While calling the directory_contents() method from the main(), we need to specify the path of the directory. While specifying the path, insert a backslash(\) at every backslash as a single backslash indicates an escape character. For example, if the path is ‘C:\Users\hello\Downloads’, then write it as ‘C:\\Users\\hello\\Downloads’.

Also read, Get all files in a directory with a specific extension in C++

Leave a Reply

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