Recursive version of LS in c programming
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
void listFilesRecursively(char *basePath) {
char path[1000];
struct dirent *dp;
DIR *dir = opendir(basePath);
if (!dir)
return;
while ((dp = readdir(dir)) != NULL) {
if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0) {
printf("%s/%s\n", basePath, dp->d_name);
// Construct new path from our base path
strcpy(path, basePath);
strcat(path, "/");
strcat(path, dp->d_name);
listFilesRecursively(path);
}
}
closedir(dir);
}
int main() {
char path[1000];
printf("Enter path: ");
scanf("%s", path);
listFilesRecursively(path);
return 0;
}
Explanation:
The above code is a recursive version of the ls
command in C programming language. It recursively lists all the files and directories present in a given directory and its subdirectories.
- The
listFilesRecursively
function takes abasePath
as input, which represents the directory to start listing files/directories from. - It initializes a character array
path
to store the complete path of each file/directory. - It opens the directory using the
opendir
function and returns a pointer to the directory stream. - If the directory cannot be opened (e.g., due to insufficient permissions), the function returns immediately.
- It then enters a
while
loop, which reads the directory entries one by one using thereaddir
function. - For each entry, it checks if the entry name is not
"."
(current directory) or".."
(parent directory). - If the entry is not
"."
or".."
, it prints the complete path of the file/directory usingprintf
. - It then constructs the new path by appending the entry name to the
basePath
usingstrcpy
,strcat
, andstrcat
functions. - Finally, it calls the
listFilesRecursively
function recursively with the new path as the argument. - This recursive call enables the function to traverse through subdirectories and list their files/directories as well.
- The function continues this process until all files/directories in the given directory and its subdirectories have been listed.
- After the
while
loop ends, the function closes the directory stream using theclosedir
function.
The main
function prompts the user to enter a directory path using printf
and scanf
.
It then calls the listFilesRecursively
function with the entered path as the argument. Finally, it returns 0 to indicate successful program execution.