首页 > 解决方案 > 如何在c中递归列出目录的所有文件

问题描述

这是一个递归列出目录下所有文件的 ac 程序,因此它可以列出 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);
}

谢谢 :)

标签: cfiledirent.h

解决方案


我一辈子都想不通为什么有人想通过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;
  }

推荐阅读