C Program to list all files and sub-directories in a directory


Here, we are given a directory. Our task is to create a C program to list all files and sub-directories in a directory.

The directory is a place/area/location where a set of the file(s) will be stored.

Subdirectory is a directory inside the root directory, in turn, it can have another sub-directory in it.

In C programming language you can list all files and sub-directories of a directory easily. The below program will illustrate how to list all files and sub-directories in a directory.

//C program to list all files and sub-directories in a directory

Example

 Live Demo

#include <stdio.h>
#include <dirent.h>
int main(void){
   struct dirent *files;
   DIR *dir = opendir(".");
   if (dir == NULL){
      printf("Directory cannot be opened!" );
      return 0;
   }
   while ((files = readdir(dir)) != NULL)
   printf("%s
", files->d_name);    closedir(dir);    return 0; }

Output

cprograms
..
prog1.c
prog2.c
prog3.c
...
prog41.c
This will return all files and sub-directory of the current directory.

Updated on: 17-Jul-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements