Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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

like image 968
zhangke Avatar asked Feb 10 '17 07:02

zhangke


People also ask

How do I open a file descriptor in Linux?

On Linux, the set of file descriptors open in a process can be accessed under the path /proc/PID/fd/ , where PID is the process identifier. File descriptor /proc/PID/fd/0 is stdin , /proc/PID/fd/1 is stdout , and /proc/PID/fd/2 is stderr .

How does open () work in C?

The open function creates and returns a new file descriptor for the file named by filename . Initially, the file position indicator for the file is at the beginning of the file.

What is DIR * in C?

Data Type: DIR. The DIR data type represents a directory stream. You shouldn't ever allocate objects of the struct dirent or DIR data types, since the directory access functions do that for you. Instead, you refer to these objects using the pointers returned by the following functions.

Are directories available through file descriptors in Linux?

File Descriptors (FD) : In Linux/Unix, everything is a file. Regular file, Directories, and even Devices are files. Every File has an associated number called File Descriptor (FD). Your screen also has a File Descriptor.


1 Answers

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.

like image 96
Barmar Avatar answered Oct 19 '22 05:10

Barmar