C++ Program to List and Display Files in the Current Directory

In this article, you will learn and get code to list and print all files and folders available in the current directory using the C++ programming language. Here "current directory" means the directory where your C++ source code is saved.

C++ List Files and Folders in the Current Directory

In C++ programming, the program below lists and displays/prints all of the files and folders (sub-directories) present in the current directory.

The question is, "Write a program in C++ to list and print all files and folders in the current directory." Here is its answer:

#include<iostream>
#include<dirent.h>
using namespace std;
int main()
{
    struct dirent *d;
    DIR *dr;
    dr = opendir(".");
    if(dr!=NULL)
    {
        cout<<"List of Files & Folders:-\n";
        for(d=readdir(dr); d!=NULL; d=readdir(dr))
        {
            cout<<d->d_name<<endl;
        }
        closedir(dr);
    }
    else
        cout<<"\nError Occurred!";
    cout<<endl;
    return 0;
}

This program was built and runs under the Code::Blocks IDE. Here is its sample run:

C++ program list all files in directory

Note: The names with extensions are files, whereas the names without extensions are folders.

As you can see, all the files and folders get printed in the output given above. The following is a screenshot of the actual folder (current directory):

list files in directory c++

In C++, using a while loop, print the files and folders in the current directory

This program does the same job as the previous program, but uses a while loop instead of a for loop.

#include<iostream>
#include<dirent.h>
using namespace std;
int main()
{
    struct dirent *d;
    DIR *dr;
    dr = opendir(".");
    if(dr!=NULL)
    {
        cout<<"List of Files and Folders:-\n";
        while((d=readdir(dr))!=NULL)
            cout<<d->d_name<<endl;
        closedir(dr);
    }
    else
        cout<<"\nError Occurred!";
    cout<<endl;
    return 0;
}

This program also displays the names of files and folders available in the current directory.

The same program in different languages

C++ Quiz


« Previous Program Next Program »