0

到目前为止,我在堆栈溢出时发现了这个,但这只会打印出当前目录而不是子目录。提前致谢!

DIR *dir;
struct dirent *ent;

if ((dir = opendir ("c:\\src\\")) != NULL) {
    /* print all the files and directories within directory */
    while ((ent = readdir (dir)) != NULL) {
        printf ("%s\n", ent->d_name);
    }
    closedir (dir);
} else {
    /* could not open directory */
    perror ("");
    return EXIT_FAILURE;
}
4

2 回答 2

7

提供以下内容,恕我直言,接受的答案不起作用。那一个只打印目录并且不能正确递归。

#include <sys/types.h>
#include <sys/param.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>

static int listDir_helper(char* path) {
  char slash = '\\';  // or maybe slash = '/'
  DIR* dir;
  struct dirent *ent;
  char *NulPosition = &path[strlen(path)];
  if ((dir = opendir(path)) != NULL) {

    while ((ent = readdir(dir)) != NULL) {
      printf("%s%c%s\n", path, slash, ent->d_name);
      if (ent->d_type == DT_DIR) {
        if ((strcmp(ent->d_name, ".") != 0) && (strcmp(ent->d_name, "..") != 0)) {
          sprintf(NulPosition, "%c%s", slash, ent->d_name);
          if (listDir_helper(path)) {
            closedir(dir);
            return 1;
          }
          *NulPosition = '\0';
        }
      }
    }

  }
  closedir(dir);
  return 0;
}

int listDir(const char* path){
  struct dirent *ent;
  char pathmax[MAXPATHLEN+1+sizeof(ent->d_name)+1];
  if (strlen(path) > MAXPATHLEN) {
    return 1;
  }
  strcpy(pathmax, path);
  return listDir_helper(pathmax);
}

int main() {
  listDir2("C:\\tmp");
  return 0;
}
于 2013-10-14T18:34:15.420 回答
5

Using your code as an example you can do: This way it will get each directory and call the function again until it cannot find a directory. And each call will do the same Its just an example.

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

void listDir(char* path){
DIR* dir;
struct dirent *ent;
  if((dir=opendir(path)) != NULL){
    while (( ent = readdir(dir)) != NULL){
      if(ent->d_type == DT_DIR && strcmp(ent->d_name, ".") != 0  && strcmp(ent->d_name, "..") != 0){
        printf("%s\n", ent->d_name);
        listDir(ent->d_name);
      }
    }
    closedir(dir);
  }
}
void main(){
  listDir(".");
}
于 2013-10-14T17:14:27.357 回答