问题
#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:
EISDIRpathname refers to a directory and the access requested involved writing (that is,O_WRONLYorO_RDWRis 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