troubleshooting Question

Recursive directory reader in C

Avatar of rockymagee
rockymagee asked on
11 Comments2 Solutions3770 ViewsLast Modified:
I have this code so far, I know I need to add recursion to the equation:

If you run it you can see that I can get to all the files in the root of C:, but I
am having trouble recursing through to the subfolders .... and thier subfolders, etc...

I am not sure how to add the recursive flow to the opendir() and readdir() functions.

?????? readdir() moves to the next item in the directory ??????

/********** BEGIN OF CODE**********/
#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>

   char *path;
   char file_name[4096];
   char *newDir;
   char newPath[100];
   DIR * directory;
   DIR * subDirectory;
   struct dirent *dir_result;
   struct stat stat_buf;
   int stat_result;

      path = "C:\\";
      printf("%s\n", path);
      directory = opendir(path);
      dir_result = readdir(directory);
      while ( dir_result != NULL) {
         dir_result = readdir(directory);

      sprintf(file_name, "%s\%s", path, dir_result->d_name);
      stat_result = stat(file_name, &stat_buf);    
         if (S_ISDIR(stat_buf.st_mode)){
            printf("%s\n", file_name);
            newDir = dir_result->d_name;
            newPath[0] = '\0';
            strcat(newPath, path);
            strcat(newPath, newDir);
            strcat(newPath, "\\");
            printf("%s\n", newPath);
            subDirectory = opendir(newPath);
            // traverse();
/********** END OF CODE**********/

If I am way off the path to doing this correctly, suggestions would also be
very much welcome ....

Kent Olsen
Data Warehouse / Database Architect

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 2 Answers and 11 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 11 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros