0

It's possible to read a regular file or a symbolic link file ( not the file it's pointing to ).

Is there a way to read the content of a directory file in a file reading fashion (e.g. fread()) .

DarkTrick
  • 2,447
  • 1
  • 21
  • 39
  • The succinct answer is via the [`opendir()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/opendir.html), [`readdir()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/readdir.html), and [`closedir()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/closedir.html) functions, and their relatives. You can no longer use `fread()` or `read()` on directories, for a variety of reasons. – Jonathan Leffler Jan 09 '20 at 03:25
  • `readlink` reads the contents of a link. `opendir` and `readdir` work with directory structures. – Serge Jan 09 '20 at 03:27
  • Related questions: [Why is `stat()` not working after `readdir()`?](https://stackoverflow.com/q/34168266/15168) and [`stat()` error ENOENT with `readdir()`](https://stackoverflow.com/q/5125919/15168) — and there are probably more direct duplicate answers too. – Jonathan Leffler Jan 09 '20 at 03:28
  • 1
    Why using `read()` doesn't work — [Using the `read()` system call on a directory?](https://stackoverflow.com/q/17618472/15168). Also [Linux C — read a directory](https://stackoverflow.com/q/17131901/15168) and [How to read all the text files in a folder using C](https://stackoverflow.com/q/11736060/15168). The latter overlaps with the two `stat()`-related questions in my previous comment. – Jonathan Leffler Jan 09 '20 at 03:37
  • @JonathanLeffler What do all those `stat()` questions have to do with this? – Barmar Jan 09 '20 at 03:42
  • They represent the problems that come next, after you've started using `readdir()` et al — @Barmar. They're not duplicates; they are simply related, and have more code than some of the others. If you've got a good duplicate for this, I'm open to suggestions. – Jonathan Leffler Jan 09 '20 at 03:44
  • I already made it dupes of the read calls. The problem of not prepending the directory affects anything that tries to use the results of reading, not just `stat()`. We see mistakes like that in just about every language that provides a similar directory-reading API. – Barmar Jan 09 '20 at 03:47
  • @JonathanLeffler: https://stackoverflow.com/a/17624304/6702598 was exactly what I was searching for. Especially this extract: **In modern times there are many kinds of filesystems that can be mounted by Linux and other unix-like systems (ext4, ZFS, NTFS!), some of which have complex directory formats. You can't do anything sensible with the raw bytes of an arbitrary directory. So the kernel has taken on the responsibility of providing a generic interface to directories as abstract objects. readdir is the central piece of that interface.** – DarkTrick Jan 09 '20 at 09:55

0 Answers0