C Program to List All Files and Subdirectories in a Directory

In this article, you will get the code for listing and printing all the files and sub-directories present in the current directory. For example, if there are 3 files and 2 folders available in the current directory, Then the program given below will list all these files and folders as output.

Print the names of files and folders in a directory

Here is a C program that will print out all of the files (without regard for extension) and folders in the directory where the source code is saved:

#include<stdio.h>
#include<conio.h>
#include<dirent.h>
int main()
{
    struct dirent *d;
    DIR *dr;
    dr = opendir(".");
    if(dr!=NULL)
    {
        printf("List of Files & Folders:-\n");
        for(d=readdir(dr); d!=NULL; d=readdir(dr))
        {
            printf("%s\n", d->d_name);
        }
        closedir(dr);
    }
    else
        printf("\nError occurred while opening the current directory!");
    getch();
    return 0;
}

This program was built and runs in the Code::Blocks IDE. Here is its sample run:

c print files folders in directory

The function opendir(".") opens a directory stream for the current directory. Here "current directory" means the directory where your above source code (program) is saved. It returns a pointer to the directory stream. And its stream gets positioned to point to the first entry in the current directory.

Note: The function opendir() returns NULL if anything strange happened while opening the directory.

And the function readdir(dr) reads the name of files or folders using the dr pointer of the DIR type.

The function readdir(dr) is implemented using the for loop, its return value is initialized to d, and it is checked whether d is equal to NULL or not. It returns NULL if anything strange happened while reading the directory (strange may be in the form that no files or folders were found or remain to be read). Whenever it is equal to NULL, program flow exits from the loop and closes the directory using closedir (dr).

Using a while loop, print the names of files and folders

Let's create the same program using a while loop.

#include<stdio.h>
#include<conio.h>
#include<dirent.h>
int main()
{
    struct dirent *d;
    DIR *dr;
    dr = opendir(".");
    if(dr!=NULL)
    {
        printf("List of Files & Subdirectories:-\n");
        while((d=readdir(dr))!=NULL)
            printf("%s\n", d->d_name);
        closedir(dr);
    }
    else
        printf("\nError occurred while opening the current directory!");
    getch();
    return 0;
}

It will produce the same output as the previous one. Here is its sample run:

c program list all files in directory

The same program in different languages

C Quiz


« Previous Program Next Program »


Liked this post? Share it!