Linux C如何打开目录并获取文件描述符

zha*_*gke 6 c linux

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>

int main()
{
    int fd;
    if ((fd = open("/home/zhangke", O_DIRECTORY | O_RDWR)) ==-1)
    {
        printf("error %s\n", strerror(errno));
       return -1;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

/home/zhangke 一个目录,它存在.我得到的错误Is a directory,所以,我该如何使用open()获得fd的目录是否正确?

Bar*_*mar 10

使用O_RDONLY而不是O_RDWR作为访问模式.从open(2)错误列表:

EISDIRpathname是指一个目录,所请求的访问涉及写入(即O_WRONLYO_RDWR已设置).