1

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.

slm
  • 369,824
Nht_e0
  • 43

3 Answers3

1

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.

thrig
  • 34,938
1

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()

schily
  • 19,173
0

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.

AdminBee
  • 22,803