简体   繁体   English

如何在 C 中使用 open() function 打开目录?

[英]How can I open directory with open() function in C?

I want to open a directory without using <dirent.h>.我想在不使用 <dirent.h> 的情况下打开一个目录。 I tried this:我试过这个:

#include <fcntl.h>

int fd = open("dir", O_RDONLY, 0);

But it returns fd = -1.但它返回 fd = -1。 Why?为什么? As I know, the directory is a file too, it just stores the location of children files and directories.据我所知,目录也是一个文件,它只存储子文件和目录的位置。

You can open directories with open, but what you probably want is the function opendir .您可以使用 open 打开目录,但您可能想要的是 function opendir

You will benefit from reading the manual page for open, especially the parts about O_PATH and O_DIRECTORY .您将从阅读手册页中受益,尤其是关于O_PATHO_DIRECTORY的部分。

To learn the details of the directory reading ABI, read the source of opendir/readdir in your C library.要了解读取 ABI 目录的详细信息,请阅读 C 库中的 opendir/readdir 的源代码。

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

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