1

I've heard everything in Linux, including directories, is a file. So I tried to access a directory file but when I tried to read it with cat I got the error cat: xp: Is a directory. Using less, more, head, tail and nl gave similar results and using Vim landed me in some kind of navigational menu.

So since I seem to be unable to find out myself I came here in search of answers.

So... What kind of information do directory files contain?

I assume that the answer includes some kind of links to the inodes of the files in that directory but what other kind of information does it contain?

Also is there a way to access the file and possibly edit it?

1 Answers1

3

Directories are files in that they often have an inode structure and data blocks are reserved from the like they are for any other file.

Directory must contain some data structure containing file names and the corresponding inode numbers. That structure might be a simple list, or some kind of a tree, that's an implementation detail. On some filesystems, some of the inode data (like the file type, which is unchanging) is also duplicated in the directory for faster access. (And of course, if the FS is VFAT, then the directory entry pretty much is the inode too.)

Linux disallows reading the contents of a directory with read(), probably because the raw data would be useless for userspace, since it would be different on different file systems, and the userspace program would need to know about the internal structure of all filesystem to be able to make use of it. Or alternatively, the kernel would need to have each filesystem present a compatible view of the directories, but that's what the getdents()/readdir() calls are for.

Some other Unixen may allow reading the directory contents, e.g. at least older versions of FreeBSD do allow it. But even on those, you probably should use readdir().

Most of the utilities just try to read the directory as they would read a regular file, leading to that error, but smart editors like Vim, and possibly less with some scripts use the directory system calls instead and produce a textual listing for you.

You can do some directory editing with special tools like debugfs for ext2/ext3/ext4. But I don't think even it allows arbitrary edits of the raw data, that sounds like a recipe for getting errors when accessing the directory, or having the filesystem driver crash.

ilkkachu
  • 138,973