2
int indent = 0;
int listDir(const char* dirname){
    DIR* dir;
    struct dirent* d;
    if(!(dir = opendir(dirname)))
        return -1;
    while((d = readdir(dir)) != NULL){
        if(strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0 ){
            continue;
        }
        else if(d->d_type != DT_DIR){ // Any except folders.
            printf("%*s- %s:%ld\n", indent, "", d->d_name, d->d_ino);
        }
        else if(d->d_type == DT_DIR){ // Folders only
            printf("%*s[%s]\n", indent, "", d->d_name);
            char path[1024];
            snprintf(path, sizeof(path), "%s/%s", dirname, d->d_name);
            indent +=2;
            listDir(path);
            indent -=2;
        }

这个函数工作得很好,但唯一的事情是它输出以下结果作为示例: 上述函数的输出

我需要输出是容器文件夹、文件和文件夹。文件夹应位于列表的末尾。例如,上面的输出应该是:

在此处输入图像描述

4

1 回答 1

5

我会说你有两个选择:

  1. 将所有readdir()结果插入到排序的数据结构中(或者只是将它们放入某个数组中并对其进行排序)。而且-我的意思是按照“文件<目录且没有其他顺序”的意思进行排序。
  2. 阅读所有条目两次- 一次,忽略所有子目录并仅打印文件;然后使用rewinddir(),然后再次读取所有条目,忽略所有常规文件并仅打印子目录。

选项 2 可能更简单 - 但有更多的库调用和系统调用。

于 2019-12-31T22:34:53.713 回答