codescracker
c

C Program to List all Files & Subdirectories in a Directory



« Previous Program Next Program »

In this article, you will get the code about listing and printing all the files and subdirectories 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 list down all these files and folders as output.

Print Files & Folders Name in a Directory

Here is the program written in C language that will print out all the files (without caring about extension) and folders in a directory where the source code is saved:

// Print all Files and Folders (subdirectories) in current Directory
// ----codescracker.com----

#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 build and run under Code::Blocks IDE. Here is its sample run:

c print files folders in directory

The function opendir(".") opens a directory stream for 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 the first entry of the current directory.

Note - The function opendir() returns NULL, if anything strange happed while opening the directory.

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

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

Using while Loop

Let's create the same program using while loop

// ----codescracker.com----

#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 same output as of previous one. Here is its sample run:

c program list all files in directory

Same Program in Other Languages


« Previous Program Next Program »