#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?
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 .
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.
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.
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.
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
orO_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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With