简体   繁体   中英

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

#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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM