How can I get the list of files in a directory using C or C++?


How can I determine the list of files in a directory from inside my C or C++ code?

I'm not allowed to execute the ls command and parse the results from within my program.

10/7/2018 1:59:17 AM

Accepted Answer

In small and simple tasks I do not use boost, I use dirent.h which is also available for windows:

DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\src\\")) != NULL) {
  /* print all the files and directories within directory */
  while ((ent = readdir (dir)) != NULL) {
    printf ("%s\n", ent->d_name);
  closedir (dir);
} else {
  /* could not open directory */
  perror ("");
  return EXIT_FAILURE;

It is just a small header file and does most of the simple stuff you need without using a big template-based approach like boost(no offence, I like boost!).

The author of the windows compatibility layer is Toni Ronkko. In Unix, it is a standard header.

UPDATE 2017:

In C++17 there is now an official way to list files of your file system: std::filesystem. There is an excellent answer from Shreevardhan below with this source code:

#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main()
    std::string path = "/path/to/directory";
    for (const auto & entry : fs::directory_iterator(path))
        std::cout << entry.path() << std::endl;
1/27/2019 3:27:19 AM

Unfortunately the C++ standard does not define a standard way of working with files and folders in this way.

Since there is no cross platform way, the best cross platform way is to use a library such as the boost filesystem module.

Cross platform boost method:

The following function, given a directory path and a file name, recursively searches the directory and its sub-directories for the file name, returning a bool, and if successful, the path to the file that was found.

bool find_file(const path & dir_path,         // in this directory,
               const std::string & file_name, // search for this name,
               path & path_found)             // placing path here if found
    if (!exists(dir_path)) 
        return false;

    directory_iterator end_itr; // default construction yields past-the-end

    for (directory_iterator itr(dir_path); itr != end_itr; ++itr)
        if (is_directory(itr->status()))
            if (find_file(itr->path(), file_name, path_found)) 
                return true;
        else if (itr->leaf() == file_name) // see below
            path_found = itr->path();
            return true;
    return false;

Source from the boost page mentioned above.

For Unix/Linux based systems:

You can use opendir / readdir / closedir.

Sample code which searches a directory for entry ``name'' is:

len = strlen(name);
dirp = opendir(".");
while ((dp = readdir(dirp)) != NULL)
        if (dp->d_namlen == len && !strcmp(dp->d_name, name)) {
                return FOUND;
return NOT_FOUND;

Source code from the above man pages.

For a windows based systems:

You can use the Win32 API FindFirstFile / FindNextFile / FindClose functions.

The following C++ example shows you a minimal use of FindFirstFile.

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

void _tmain(int argc, TCHAR *argv[])
   WIN32_FIND_DATA FindFileData;
   HANDLE hFind;

   if( argc != 2 )
      _tprintf(TEXT("Usage: %s [target_file]\n"), argv[0]);

   _tprintf (TEXT("Target file is %s\n"), argv[1]);
   hFind = FindFirstFile(argv[1], &FindFileData);
   if (hFind == INVALID_HANDLE_VALUE) 
      printf ("FindFirstFile failed (%d)\n", GetLastError());
      _tprintf (TEXT("The first file found is %s\n"), 

Source code from the above msdn pages.


One function is enough, you don't need to use any 3rd-party library (for Windows).

#include <Windows.h>

vector<string> get_all_files_names_within_folder(string folder)
    vector<string> names;
    string search_path = folder + "/*.*";
    WIN32_FIND_DATA fd; 
    HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd); 
    if(hFind != INVALID_HANDLE_VALUE) { 
        do { 
            // read all (real) files in current folder
            // , delete '!' read other 2 default folder . and ..
            if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {
        }while(::FindNextFile(hFind, &fd)); 
    return names;

PS: as mentioned by @Sebastian, you could change *.* to *.ext in order to get only the EXT-files (i.e. of a specific type) in that directory.


For a C only solution, please check this out. It only requires an extra header:

tinydir_dir dir;
tinydir_open(&dir, "/path/to/dir");

while (dir.has_next)
    tinydir_file file;
    tinydir_readfile(&dir, &file);

    if (file.is_dir)



Some advantages over other options:

  • It's portable - wraps POSIX dirent and Windows FindFirstFile
  • It uses readdir_r where available, which means it's (usually) threadsafe
  • Supports Windows UTF-16 via the same UNICODE macros
  • It is C90 so even very ancient compilers can use it

I recommend using glob with this reusable wrapper. It generates a vector<string> corresponding to file paths that fit the glob pattern:

#include <glob.h>
#include <vector>
using std::vector;

vector<string> globVector(const string& pattern){
    glob_t glob_result;
    vector<string> files;
    for(unsigned int i=0;i<glob_result.gl_pathc;++i){
    return files;

Which can then be called with a normal system wildcard pattern such as:

vector<string> files = globVector("./*");

Here is a very simple code in C++11 using boost::filesystem library to get file names in a directory (excluding folder names):

#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;

int main()
    path p("D:/AnyFolder");
    for (auto i = directory_iterator(p); i != directory_iterator(); i++)
        if (!is_directory(i->path())) //we eliminate directories
            cout << i->path().filename().string() << endl;

Output is like:


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]