-1

I want to open a directory without using <dirent.h>. I tried this:

#include <fcntl.h>

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

But it returns fd = -1. Why? As I know, the directory is a file too, it just stores the location of children files and directories.

  • Possible duplicate of https://stackoverflow.com/questions/42154232/linux-c-how-to-open-a-directory-and-get-a-file-descriptor – binaryRat Feb 15 '21 at 07:55

1 Answers1

0

You can open directories with open, but what you probably want is the function opendir.

You will benefit from reading the manual page for open, especially the parts about O_PATH and O_DIRECTORY.

To learn the details of the directory reading ABI, read the source of opendir/readdir in your C library.

Tom V
  • 4,827
  • 2
  • 5
  • 22
  • I know opendir() function. I'm just interested, how can I open a directory as a file? – Abdul Axundzade Feb 15 '21 at 08:01
  • why do people think a directory can be opened as a file? What do they expect to read from it? Some time ago a friend of mine asked the same because he used to launch "vim dir/" and he was able to read file list "as a file".. which of course is a vim feature – Jack Feb 15 '21 at 08:31
  • @Jack It /can/ be opened and read as a file, this is what happens inside readdir. It just isn't something that most people should want to do. – Tom V Feb 15 '21 at 09:08
  • @TomV In my system this returns -1 `read(open("/home", 0), buf, 10)`: `home` directory can't be read as file, even if the open() returns a valid file descriptor. What (and how) do you expect to read from it? – Jack Feb 16 '21 at 08:23