Get all files in a directory with a specific extension in C++

In this tutorial, we will learn how to get all files in a directory with a specific extension or file format in C++. Now, in order to find all files in a directory with a specific extension or format in C++. Lets first understand what is a file extension.

What is a file extension?

A file extension is usually what we write at the end of the filename. That specific keyword which we at the end of the filename can be understood by the operating system. And that defines what kind of particular file type it is.

For example, for a document file type its extension is .DOC, .PDF, .TXT, etc.
Any program in the C++ language is also saved with .cpp extension.

Let us understand a program in order to find(list) all the files in a directory with a specific extension. In this program lets consider the extension as .txt for obtaining all text documents.

//illustrating finding all files in 
// a directory with a .txt extensions.
#include <dirent.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    DIR *di;
    char *ptr1,*ptr2;
    int retn;
    struct dirent *dir;
    di = opendir("."); //specify the directory name
    if (di)
    {
        while ((dir = readdir(di)) != NULL)
        {
            ptr1=strtok(dir->d_name,".");
            ptr2=strtok(NULL,".");
            if(ptr2!=NULL)
            {
                retn=strcmp(ptr2,"txt");
                if(retn==0)
                {
                    printf("%s\t",ptr1);
                }
            }

        }
        closedir(di);
    }
    return(0);
}

Therefore above code, display the output as :

List all the files in particular 
directory having .txt extensions.

We can specify whichever filetype in what by specifying it at the place of txt.
It is better to use LINUX or UNIX where we can directly use ls command in order to list all the files in a directory of all types.

 

Recommended Blogs :

How to remove the Last Line from a text file in C++?

C++ program to remove a particular character from a string

 

2 responses to “Get all files in a directory with a specific extension in C++”

  1. kil47 says:

    This will not work if file extension is like .demo.txt
    But thanks for the warm up code – with little modification it can do wonders and is portable 🙂

  2. Rahul Choudhary says:

    how you correct that i am facing the same issue

Leave a Reply

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