Home  >  Article  >  Backend Development  >  C program to list all files and subdirectories in a directory

C program to list all files and subdirectories in a directory

WBOY
WBOYforward
2023-08-25 22:09:221409browse

C program to list all files and subdirectories in a directory

Here, we get a directory. Our task is to create a C program that lists all files and subdirectories in a directory.

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

Subdirectory is a directory within the root directory, which, in turn, can have another subdirectory.

In C programming language you can easily list all files and subdirectories in a directory. The following program shows how to list all files and subdirectories in a directory.

//C program to list all files and subdirectories in a directory

Example h2>

Live demonstration

#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</p><p>", 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.

The above is the detailed content of C program to list all files and subdirectories in a directory. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more