C Program to List Files in current Directory
Objective
Write a C program to list all files in the current directory.
Algorithm / Approach
- Include
<dirent.h>. - Declare a directory pointer
DIR *dand a directory entry structurestruct dirent *dir. - Open the current directory using
d = opendir("."). - Use a
whileloop to read directory entries:(dir = readdir(d)) != NULL. - Print the file name:
printf("%s\n", dir->d_name). - Close the directory using
closedir(d).
main.c
#include<dirent.h>
#include<stdio.h>
int main( ) {
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
}
return 0;
}
Expected Output
first.txt prowess.txt second.txt
Explanation of the Program
- C isn't just for processing data; it can interact directly with the Operating System's filesystem.
- The
dirent.hheader provides POSIX standard functions for directory traversal. The string"."is a universal filesystem shortcut that refers to the "Current Working Directory" (the folder where the C program is currently running from).
Complexity
Time Complexity
O(n) - Where n is the number of files in the folder.
Space Complexity
O(1)