到目前为止,我在堆栈溢出时发现了这个,但这只打印出当前目录而不是子目录。提前谢谢!
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;
}
答案 0 :(得分:6)
提供以下作为恕我直言,接受的答案不起作用。那个只打印目录而且没有正确递归。
#include <sys/types.h>
#include <sys/param.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
int listDir_helper(char* path) {
char 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(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;
}
答案 1 :(得分:5)
以您的代码为例,您可以: 这样它将获取每个目录并再次调用该函数,直到它找不到目录。 每次通话都会这样做 这只是一个例子。
#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(".");
}