cfiledirent.h

How to list all files of a directory recursively in c


This is a c program that list all files of a directory recursively , so it can list all files in c: drive for example .

The above program works fine but i've been trying for 5 days and i can't get it to work without using a function (only main , not main and the other function (listFilesRecursively) )

#include <stdio.h>
#include <string.h>
#include <dirent.h>

void listFilesRecursively(char *path);


int main()
{
    // Directory path to list files
    char path[100];

    // Input path from user
    strcpy(path , "c://");

    listFilesRecursively(path);

    return 0;
}


/**
 * Lists all files and sub-directories recursively 
 * considering path as base path.
 */
void listFilesRecursively(char *basePath)
{
    char path[1000];
    struct dirent *dp;
    DIR *dir = opendir(basePath);

    // Unable to open directory stream
    if (!dir)
        return;

    while ((dp = readdir(dir)) != NULL)
    {
        if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
        {
            printf("%s\n", dp->d_name);

            // Construct new path from our base path
            strcpy(path, basePath);
            strcat(path, "/");
            strcat(path, dp->d_name);

            listFilesRecursively(path);
        }
    }

    closedir(dir);
}

Thanks :)


Solution

  • I can't for the life of me think why anybody would want to enumerate directories by calling main() recursively. But, since I can't resist a pointless challenge, here's a version that does. Do I get the prize for "most fruitless waste of ten minutes?" ;)

    #include <stdio.h>
    #include <string.h>
    #include <dirent.h>
    #include <errno.h>
    #include <stdlib.h>
    
    int main (int argc, char **argv)
      {
      const char *path;
      if (argc != 2) path = "/etc"; /* Set starting directory, if not passed */
      else
        path = argv[1];
    
      DIR *dir = opendir (path);
      if (dir)
        {
        struct dirent *dp;
        while ((dp = readdir(dir)) != NULL)
          {
          if (dp->d_name[0] != '.')
            {
            char *fullpath = malloc (strlen (path) + strlen (dp->d_name) + 2);
            strcpy (fullpath, path);
            strcat (fullpath, "/");
            strcat (fullpath, dp->d_name);
            if (dp->d_type == DT_DIR)
              {
              char **new_argv = malloc (2 * sizeof (char *));
              new_argv[0] = argv[0];
              new_argv[1] = fullpath;
              main (2, new_argv);
              free (new_argv);
              }
            else
              printf ("%s\n", fullpath);
            free (fullpath);
            }
          }
        closedir(dir);
        }
      else
        fprintf (stderr, "Can't open dir %s: %s", path, strerror (errno));
      return 0;
      }