代码之家  ›  专栏  ›  技术社区  ›  Sachin

closeDir()导致核心转储

  •  0
  • Sachin  · 技术社区  · 16 年前

    我在unix平台上用c编写的代码有以下几行。请告诉我为什么要在closeDir()函数中转储核心。我可以成功地打开路径指定的目录。

        if (opendir(MyDir) != NULL )
        {
        closedir((DIR *) MyDir);
            exit 0;
        }
    
    3 回复  |  直到 16 年前
        1
  •  2
  •   Douglas Leeder    16 年前

    MyDir 必须是 const char* 成为 opendir .

    你需要 结果 从 打开目录 传到 closedir -你不能就这么走!

    const char* MyDir = "/";
    DIR* directory = opendir(MyDir);
    if (directory != NULL)
    {
        closedir(directory);
        exit(0);
    }
    
        2
  •  3
  •   Alok Singhal    16 年前

    closedir() takes a DIR * 不是 char * . 祝愿 闭路() 那样做是行不通的。尝试:

    #include <sys/types.h>
    #include <dirent.h>
    
    DIR *dir;
    if ((dir = opendir(MyDir)) != NULL)
        closedir(dir);
    

    而且,你好像还加了一个演员 (DIR *) MyDir 以抑制编译器警告。当编译器向您发出警告时,您应该了解它为什么这样做。压制警告几乎不是正确的做法。

        3
  •  0
  •   Giovanni Funchal    16 年前

    类型转换不正确。供参考:

    opendir 需要一个目录名(char*)作为参数并返回一个目录流(dir*):

    DIR* opendir(const char* name)
    

    closedir 需要一个目录流(dir*)作为参数,并返回一个int(0表示成功):

    int closedir(DIR* stream)
    

    所以你的代码应该是:

    const char* dirname;
    DIR* mydir;
    
    mydir = opendir(dirname);
    if(mydir != NULL) {
       closedir(mydir);
       exit(0);
    }
    

    参见: http://sunsson.iptime.org/susv3/functions/readdir.html

    推荐文章