简体   繁体   English

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

[英]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 . /home/zhangke一个目录,它是存在的。 I get error Is a directory , so, how can I use open() to get a fd of a directory correctly?我收到错误Is a directory ,那么,如何使用open()正确获取目录的fd

Use O_RDONLY instead of O_RDWR as the access mode.使用O_RDONLY而不是O_RDWR作为访问模式。 From the open(2) error list:来自open(2)错误列表:

EISDIR pathname refers to a directory and the access requested involved writing (that is, O_WRONLY or O_RDWR is set). EISDIR路径名指的是一个目录,请求的访问涉及写入(即设置了O_WRONLYO_RDWR )。

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_CREAT标志总是创建一个常规文件。 O_DIRECTORY is only meaningful when opening an existing name, it checks that the name refers to a directory. O_DIRECTORY仅在打开现有名称时才有意义,它检查该名称是否指目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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