I'm trying to sort a current working directory, sub-directories, and then display them. My program behavior begins the process and works for the first sub-directory but none after that. A few prints are to check behavior of the code. While there is a complete working version of this on stackoverflow, I just want to better understand where my code logic is failing. Any help is greatly appreciated. Here is the code:
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
void sortArr(char array[256][256], int amt) {
char temp[1000];
for(int i=0; i<amt; i++) {
for(int j=0; j<(amt-1-i); j++) {
if(strcmp(array[j], array[j+1]) > 0) {
strcpy(temp, array[j]);
strcpy(array[j], array[j+1]);
strcpy(array[j+1], temp);
}
}
}
printf("SortList: %s\n", array[0]);
}
void build(char *s_path, const int root) {
char path[1000];
strcat(path, s_path);
int amt=0,index;
struct dirent *dp;
DIR *dir =opendir(path);
char list[256][256];
struct stat statbuf;
if(!dir)
return;
while((dp =readdir(dir)) != NULL) {
if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0) {
strcpy(list[amt], dp->d_name);
amt++;
}
}
sortArr(list, amt);
for(int i=0; i <amt;i++) {
for (index=0; index<root; index++) {
if (index%2 == 0 || index == 0)
printf("%c", ' ');
else
printf(" ");
}
printf("%c %s\n", '-', list[i]);
strcpy(path, s_path);
strcat(path, "/");
strcat(path, list[i]);
stat(path, &statbuf);
if((S_ISDIR(statbuf.st_mode)) != 0 && (S_ISREG(statbuf.st_mode)) ==0) {
printf("DIR: %s\n", path);
build(path,root +2);
}
}
closedir(dir);
}
int main() {
build(".", 0);
};