How to Get all the Files in a Directory using C++

Hey Guys!! In this tutorial, we will learn how to get all the files in a directory/folder by using a simple C++ program.

For this we need to use a header file known as dirent.h which is used to represent a directory stream and  includes in the following compilers:

  • Turbo C++ (DOS)
  • GCC  (Cross-platform)
  • MinGW (a  Microsoft Windows version of GCC)
  • Borland  C++ Builder ( Microsoft Windows)

And we also need to use some functions for this such as :

  • opendir() function which opens a directory stream corresponding to the directory name and returns a pointer to the directory stream
  • readdir() function which returns a pointer to a structure representing the next directory entry in the directory stream and at last
  • closedir() function which closes the directory handle.

C++ Program to get all the files in a directory

using namespace std;
int main()
          DIR *dir;
          dirent *pdir;
          cout<<"Enter path to list all the files in a directory:"<<endl;
              cout<< pdir->d_name<<endl;
//Enter path to list all the files in a directory:
// ..
//  a.out

a.out is a default output file name when no output name is specified.

I have used some commands here such as:

DIR is a command in Various OS  as it is used for computer file and directory listing.

PDIR is a programmable DIR command as it allows us to display information about files and directories.

I hope your all query regarding this is resolved now.

If you still have any query then please let me know.

You may also check

Leave a Reply

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