my code is not working. I need to display all directories inside the directory given as the command line argument. So far I have tried this:
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
struct stat my_stat;
int searchDirectory (char *dirName);
int searchDirectory(char *dirName){
struct dirent *pDirent;
DIR *pDir;
pDir = opendir(dirName);
if (pDir == NULL) {
printf("Cannot open directory '%s'\n", dirName );
return 1;
}
while ((pDirent = readdir(pDir)) != NULL){
printf("%s\n", pDirent->d_name);
stat(pDirent->d_name, &my_stat);
if (S_ISDIR(my_stat.st_mode)){
searchDirectory(pDirent->d_name);
printf("Directory Found: %s\n", pDirent->d_name);
}
}
return 0;
}
int main(int argc, char *argv[]){
struct stat my_stat;
if (lstat(argv[1], &my_stat) < 0){
perror("stat error");
}
if (S_ISDIR(my_stat.st_mode)){
printf("Directory found\n");
searchDirectory(argv[1]);
}
return 0;
}
I am not sure why but for some reason my code is reading normal files as a directory, but S_ISDIR(my_stat.st_mode)) should prevent this. Any idea on what could be wrong?