【问题标题】:C - OpenDir() Number of EntriesC - OpenDir() 条目数
【发布时间】:2014-03-10 19:50:05
【问题描述】:

使用 opendir() 获得 DIR * 后,我需要使用 readdir() 读取 struct dirent 并将其存储到数组中。

为了弄清楚数组的大小,我可以循环遍历并计算条目。然后,我可以分配数组,然后再次循环读取和存储 struct dirent。

但是,我想知道是否有更好的方法来获取 dir 条目的数量?

【问题讨论】:

  • 您可以分配一个小数组,然后根据需要使用realloc 来增加它。
  • Iirc 在某些系统上,目录的大小(如 struct stat.st_size)是条目数量的指示,但 1. 在 some 系统上,它是绝对不便携,而且 2. 我不确定删除文件时数量是否减少了,所以我猜你的问题的答案基本上是“不,抱歉”
  • 遍历条目两次对我来说似乎是个坏主意。如果在两次传递之间创建文件会发生什么?

标签: c


【解决方案1】:

realloc 方法可能是最好的方法。这是一个示例(为演示目的选择了小分配大小。)没有执行错误检查。循环结束时,direntArray 有货,count 告诉你有多少。

#define num_to_alloc 10

int main(int argc, const char * argv[])
{

    struct dirent *direntArray = NULL;

    DIR *myDir = opendir("/tmp");
    int count = 0;
    int max = 0;
    struct dirent *myEnt;

    while ((myEnt = readdir(myDir))){
        if ( count == max ){
            max += num_to_alloc;
            direntArray = realloc(direntArray, max * sizeof(struct dirent));
        }
        memcpy(&direntArray[count], myEnt, sizeof(struct dirent));
        count++;
    }
    return 0; 
}

【讨论】:

    猜你喜欢
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 2015-06-22
    • 1970-01-01
    相关资源
    最近更新 更多