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.
dd
could copy a directory structure to a file of your choice? – Jeremy Boden Jul 28 '21 at 23:13