I have the following files/directories in my current directory. test_folder1 is a directory and there is one more directory in that directory. My C code is supposed to print all the files/directories in the current directory recursively. However, it only prints the current directory and one level down subdirectory, it does not go beyond that. Please help.
Current Directory:
a.out at.c dt dt.c main.c README test.c test_folder1.
Subdirectory of test_folder1:
ahmet.txt mehmet.txt test_folder2.
Subdirectory of test_folder2:
mahmut.txt
This for mac terminal C code.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <limits.h>
void depthFirst(DIR *dir){
struct dirent *sd;
char path[PATH_MAX];
if(dir == NULL){
printf("Error, unable to open\n");
exit(1);
}
while( (sd = readdir(dir)) != NULL){
if(strcmp(sd->d_name, ".") != 0 && strcmp(sd->d_name, "..") != 0){
printf("%s\n", sd->d_name);
realpath(sd->d_name,path);
if(isdirectory(path)){
depthFirst(opendir(sd->d_name));
}
}
}
}
int isdirectory(char *path) {
struct stat statbuf;
if (stat(path, &statbuf) == -1)
return 0;
else
return S_ISDIR(statbuf.st_mode);
}
int main(int argc, char *argv[]){
if(argc<2){
printf("No arguments");
DIR *dir;
dir = opendir(".");
depthFirst(dir);
closedir(dir);
}
This is the output
README
main.c
test.c
test_folder1
ahmet.txt
mehmet.txt
test_folder2
a.out
at.c
dt
dt.c