Read a directory to see the file to inode mapping

directoryfilesystems

I'm just learning about filesystems and it is said that a directory is just an ordinary file which keeps a list of file-inode pairs.

If I try to open the directory Downloads with any of the following cat less tail, it just outputs that its a directory and can't be opened.

Ideas how to read it?

Best Answer

A correction: the directory is a list of fileNAME-inode pairs. And it's not an "ordinary" file. Like symlinks, sockets, and device nodes, its behaviour is different from that of ordinary files.

From the shell, you can see the mapping with ls -i.

From C, the structure returned by readdir() contains a d_name and a d_ino element, from which you can also see this mapping.

From userspace, the fact that a directory maps filenames to inodes is not usually all that important, because the kernel requires that you designate files by their name anyway. It doesn't let you ask for a file by inode number.

Symbolic links are another example of a type of file which contains information that can't be read as though it were a byte stream with systems calls like read(). Like an ordinary file, it contains data. In this case the data has special meaning: it's a pathname (which is a string) naming the target of the symlink. Unlike an ordinary file, the contents are not written using write() but with symlink(), and the contents are not read using read() but with readlink().

Related Question