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

C program to list all files and subdirectories in a directory

WBOY
Release: 2023-08-25 22:09:22
forward
1435 people have browsed it

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;
}
Copy after login

Output

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template