如何在c中递归列出目录的所有文件

How to list all files of a directory recursively in c

这是一个递归列出目录下所有文件的c程序,因此它可以列出例如c:驱动器中的所有文件。

上面的程序工作正常,但我已经尝试了 5 天,如果不使用函数(只有 main ,不是 main 和其他函数 (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);
}

谢谢:)

我想不通为什么有人会想通过递归调用 main() 来枚举目录。但是,由于我无法抗拒毫无意义的挑战,这里有一个可以抗拒的版本。我会因为“浪费十分钟最无结果”而获奖吗? ;)

#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;
  }