4

In it's main page it says:

fchdir() is identical to chdir(); the only difference is that the directory is given as an open file descriptor.

And the prototype is given as following:

int chdir(const char *path);
int fchdir(int fd);

My question is how can a directory be passed as a file descriptor? Do directories also have a corresponding descriptor like files?

EugenSunic
  • 13,162
  • 13
  • 64
  • 86
UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54
  • no answer but maybe interesting for you https://en.wikipedia.org/wiki/Everything_is_a_file – thumbmunkeys Sep 24 '15 at 12:42
  • You have some info here: http://stackoverflow.com/questions/18192998/plain-c-opening-a-directory-with-fopen – Ôrel Sep 24 '15 at 12:43
  • Also if you have used `opendir` to open the directory, you can get the file descriptor from the `DIR *` with `dirfd()` –  Sep 24 '15 at 12:58

2 Answers2

5

Do directories also have a corresponding descriptor like files?

Yes. The Unix philosophy(and Linux) is to treat everything as a stream of bytes. So yes, you can do open(2) on a directory and get its file descriptor. Not only directories but sockets, pipes and devices can also be opened using open(2) system call and do operations on it as though it's a file.

P.P
  • 117,907
  • 20
  • 175
  • 238
2

As you can read on the Opengroup documentation for fchdir,

A conforming application can obtain a file descriptor for a file of type directory using open(), provided that the file status flags and access modes do not contain O_WRONLY or O_RDWR.

So by calling open on a directory, one obtains a file descriptor to a directory. So in a sense, yes, all directories have file descriptors.

The underlying OS takes care to map the file descriptors to the proper filesystem object, thus abstracting away whatever this object may be at the lowest level.

rubenvb
  • 74,642
  • 33
  • 187
  • 332