Can we use read()
, write()
on a directory just like on any other file in Unix/Linux? I have a confusion here because directories are also considered as files.
-
2Does this answer your question? How does one inspect the directory structure information of a unix/linux file? – G-Man Says 'Reinstate Monica' Feb 28 '24 at 00:28
3 Answers
not really, no, there are dedicated
directory, opendir, closedir, dirfd, fdopendir, readdir, readdir_r,
rewinddir, seekdir, telldir(3) - directory operations
functions for operations on directories (those are from OpenBSD) and modern filesystems (or really anything in decade or two or more) in no way encode directories as plain files.

- 34,938
Some filesystems allow to use read()
on directories, but this must be seen as a mistake since the data structures in such a directory may be undocumented.
You never can use write()
since this would destroy the integrity of the affected directory.
The official interfaces for directories are opendir(), closedir() readdir(), telldir(), seekdir()

- 19,173
I have a book from 1986 that cites using read()
for reading dirctories.
It's named The Design Of The UNIX Operating System and this use is mentioned on page 10, but this code does not work on my modern Ubuntu.
Asking around Google and GPT it seems that at 1988 there was already a dedicated readdir()
function, so that has changed.

- 22,803