C

C Program To List All Files in a Directory

In this tutorial, we are going to see how to write a C program to list all files present in a directory or a folder in which the executable file of this program is present. For example, if the executable file is present in “C:\Users\Pc”, it will list all the files present in “C:\Users\Pc”. In this tutorial we are going to use the header file dirent.h of the C library which contains structures facilitating the navigation in the directories, as described below in the program.
 

C Program To List All Files in a Directory
#include <dirent.h>
#include <stdio.h>
 
int main()
{
    struct dirent *dir;
    // opendir() returns a pointer of type DIR. 
    DIR *d = opendir("."); 
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            printf("%s\n", dir->d_name);
        }
        closedir(d);
    }
    return 0;
}

Output:
 

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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