codescracker
c++

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



« Previous Program Next Program »

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

C++ List Files and Folders in Current Directory

The program given below lists and displays/prints all the files and folders (subdirectories) present inside the current directory in C++ programming.

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

// C++ Print all Files and Folders (Subdirectories)
// ----codescracker.com----

#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 build and run under Code::Blocks IDE. Here is its sample run:

C++ program list all files in directory

Note - The name with extension are files, whereas name without extension are folders.

As you can see, all the files and folders gets printed in the output given above. Here is the snapshot of the actual folder (current directory):

list files in directory c++

Print Files/Folders of Current Directory using while Loop

This program does the same job as of previous program, but using while loop, instead of for loop

// Print Files/Folders using while Loop
// ----codescracker.com----

#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 display the name of files and folders available in current directory.

Same Program in Other Languages

C++ Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker