如何编写一个函数,返回一个目录中的所有文件名,包括子目录中的文件。 到目前为止,我有类似的东西,但它不能正常工作,我尝试调用这个函数并打印出每个元素,它只打印第一个元素。
谁能告诉我我做错了什么或编写此函数的其他方法?
char **allFiles(char *dir, OPTIONS opts) {
char **allfiles = malloc(sizeof(char **));
struct dirent *dp;
while((dp = readdir(dirp)) != NULL) {
if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
continue;
if (dp->d_type == DT_DIR)
allfiles = allFiles(strcat(strcat(dir, "/"), dp->d_name));
if (dp->d_type != DT_DIR)
*allfiles = strdup(strcat(strcat(strdup(dir), "/"), dp->d_name));
++allfiles;
}
closedir(dirp);
return allfiles;
}
最佳答案
allfiles[] 数组由父项和递归子项填充。 child 插入其中,但结果被 parent 覆盖。
更新:重读后,我发现数组管理看起来还不错(除了可能超限之外) 也许您用完了文件描述符?
更新2:替换
if (dp->d_type != DT_DIR)
*allfiles = strdup(strcat(strcat(strdup(dir), "/"), dp->d_name));
++allfiles;
通过:
if (dp->d_type != DT_DIR)
*allfiles++ = strdup(strcat(strcat(strdup(dir), "/"), dp->d_name));
关于c: 返回目录中的所有文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7927948/