开发者

closedir () causing core dumped

开发者 https://www.devze.com 2022-12-17 22:37 出处:网络
I have below lines in my code written in C on unix platform. Please let me know why I am getting core dumped in closedir() function. I could successfully opened the directory specified by path.

I have below lines in my code written in C on unix platform. Please let me know why I am getting core dumped in closedir() function. I could successfully opened the directory specified by path.

开发者_运维技巧
    if (opendir(MyDir) != NULL )
    {
    closedir((DIR *) MyDir);
        exit 0;
    }


closedir() takes a DIR *, not a char *. Wishing closedir() did that is not going to work. Try:

#include <sys/types.h>
#include <dirent.h>

DIR *dir;
if ((dir = opendir(MyDir)) != NULL)
    closedir(dir);

Also, it seems you added a cast in (DIR *) MyDir to suppress a compiler warning. When a compiler gives you a warning, you should find out why it is doing so. Suppressing the warning is hardly the right thing to do.


MyDir must be a const char* to be the argument for opendir.

You need the result from opendir to pass to closedir - you can't just cast the path!

const char* MyDir = "/";
DIR* directory = opendir(MyDir);
if (directory != NULL)
{
    closedir(directory);
    exit(0);
}


the typecast is incorrect. For reference:

opendir needs a directory name (char*) as parameter and returns a directory stream (DIR*):

DIR* opendir(const char* name)

closedir needs a directory stream (DIR*) as parameter and returns an int (0 on success):

int closedir(DIR* stream)

So your code should look like:

const char* dirname;
DIR* mydir;

mydir = opendir(dirname);
if(mydir != NULL) {
   closedir(mydir);
   exit(0);
}

See also: http://sunsson.iptime.org/susv3/functions/readdir.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号