Linux C how to open a directory and get a file descriptor

爷,独闯天下 提交于 2021-02-19 00:50:32

问题


#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;
}

/home/zhangke is a directory and it exists. I get error Is a directory, so, how can I use open() to get a fd of a directory correctly?


回答1:


Use O_RDONLY instead of O_RDWR as the access mode. From the open(2) error list:

EISDIR pathname refers to a directory and the access requested involved writing (that is, O_WRONLY or O_RDWR is set).

As far as I can tell, there's no way to create and open a directory atomically. The O_CREAT flag always creates a regular file. O_DIRECTORY is only meaningful when opening an existing name, it checks that the name refers to a directory.



来源:https://stackoverflow.com/questions/42154232/linux-c-how-to-open-a-directory-and-get-a-file-descriptor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!