So I'm struggling on a recursive function to enter a directory and it's subdirectories to save all the file names and a counter for the number of files. I don't know if this is the best way to save the file names, but I don't see any other way. I'm having problems passing the array of pointers and the file counter to the function.
Sorry for any absurd code.
Here's what I have:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <dirent.h> int main(int argc, char *argv[]) { char * path = argv[1]; char ** tempFiles = NULL; int fileCounter = 0; findFilesRecursive(&fileCounter, &tempFiles, path); for (int i = 0; i < fileCounter; i++) printf("\n[%d]: %s", i, tempFiles[i]); } void findFilesRecursive(int * fileCounter, char ** tempFiles, char * path) { DIR * dirStream; struct dirent * entry; if(!(dirStream = opendir(path))) return; while ((entry = readdir(dirStream)) != NULL) { if (entry->d_type == DT_DIR) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; char fullPath[strlen(path) + strlen(entry->d_name) + 1]; sprintf(fullPath, "%s%s/", path, entry->d_name); findFilesRecursive(&(*fileCounter), &tempFiles, fullPath); } else if (entry->d_type == DT_REG) { char filePath[strlen(path) + strlen(entry->d_name)]; sprintf(filePath, "%s%s", path, entry->d_name); printf("FILE: %s\n", filePath); tempFiles = (char **) realloc(tempFiles, (*fileCounter + 1) * sizeof(char *)); tempFiles[*fileCounter] = (char *) MALLOC(strlen(filePath) * sizeof(char)); strcpy(tempFiles[*fileCounter], filePath); (*fileCounter)++; } } closedir(dirStream); }
if (entry->d_type == DT_DIR) {and pass a pointer to it, instead of a shared variable. That way you don't need to rely on it to be initialised properly. And to avoid too many reallocs you could have created a structure that holds a pointer to a pointer to a char and additional fields that could hold say current capacity and number of elements in a collection.tempFilesto any sane value. You pass its address tofindFilesRecursive, and then pass that address torealloc. That doesn't make any sense -- you can only usereallocto either get a brand new block (in which case, you must pass itNULL) or to enlarge an existing block you got frommallocorrealloc.