In this tutorial you will learn about the C Program to List Files in Directory and its application with practical example.
C Program to List Files in Directory
In this tutorial, you will learn about the C Program to List Files in Directory with a practical example.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- Concepts of while loop.
- Conditional Statements in C programming.
- Using file functions of c language.
Program to List Files in Directory
As we all know the file is a collection of characters, integers, and many data types. In strings, only one variable is declared which can store multiple values. First will take the file from the user. Then will Check that directory if it’s empty or not. The C programming language has many pre-defined functions for file manipulation. but in today’s tutorial, we will List Files in Directory.
With the help of this program, we can List Files in the Directory
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables for the program. 2. Taking the input from the user. 3. Reading the directory. 4. <strong>Viewing the directory </strong>if there are any files. 5. Printing the results data. 6. End program. |
Program:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <stdio.h> #include <dirent.h> int main() { //declaring the variables for the program struct dirent *de; // Pointer for directory entry // opendir() returns a pointer of DIR type. DIR *dr = opendir("."); if (dr == NULL) // opendir returns NULL if couldn't open directory { printf("Could not open current directory" ); return 0; } // Refer http://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html // for readdir() while ((de = readdir(dr)) != NULL) printf("%s\n", de->d_name); closedir(dr); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- *de = it will hold the address value.
- *dr = it will hold the dir data.
Opening and reading the directory.
Reading the directory if empty then.
Generating the list and printing the list of files present in the directory using the while loop.