C/C++ : Get List Files in Directory

I have a problem when want to get list of files in directory or get list of directory and subdirectory using C++. So, I have try to research this problem and get a simple method using dirent library. Please check below code to get list of files in directory or get list of directory and subdirectory using C++.

Create file with name list_file.cpp. Copy code below :

#include <stdio.h>
#include <dirent.h>
#include <iostream>
#include <string>
#include <sys/stat.h>

using namespace std;

bool isDir(string dir)
{
    struct stat fileInfo;
    stat(dir.c_str(), &fileInfo);
    if (S_ISDIR(fileInfo.st_mode))
        return true;
    else
        return false;
}

void listFiles(string baseDir, bool recursive)
{
    DIR *dp;
    struct dirent *dirp;

    string separator;
#ifdef linux
    separator = "/";
#elif _WIN32
    separator = "\\";
#endif
    if ((dp = opendir(baseDir.c_str())) == NULL) 
    {
        cout << "[ERROR: " << errno << " ] Couldn't open " << baseDir << "." << endl;
        return;
    } 
    else 
    {
        while ((dirp = readdir(dp)) != NULL) 
        {
            if (dirp->d_name != string(".") && dirp->d_name != string("..")) 
            {
                string aa = baseDir + separator + dirp->d_name;
                if (isDir(aa) == true) 
                {
                    cout << "[DIR]\t" << baseDir << dirp->d_name <<  endl;
                    if(recursive == true)
                        listFiles(aa, true);
                } 
                else 
                    cout << "[FILE]\t" << aa <<endl;
            }
        }
        closedir(dp);
    }
}

int main(int argc, char **argv)
{
	string path = "C:\\temp";
	listFiles(path, false);

	return(1);
}

Compile code to get list of files in directory or get list of directory and subdirectory using C++ using command :

g++ list_file.cpp -o list_file

if you set listFiles function in second argument to false, we can get only list of files and directory in current directory. Example, the output from my computer is like this (setting argument to false)

C:\temp>list_files
[FILE]  C:\temp\main.cpp
[FILE]  C:\temp\main.exe
[DIR]   C:\tempdirectory
[FILE]  C:\temp\tempdirectory_04112014.zip

But, if you set the second argument to true, we will get list of files and directory in sub directory. I hope this code can help you to get list of files in directory or get list of directory and subdirectory using C++.

Add a Comment

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