Linux – How is it possible for empty files to take zero bytes in Linux

disk-spaceext4filesystemshard drivelinux

I've also asked a sibling question for Windows.


In Linux (I just tested):

  • The size of an empty folder is given as 4 KB (regardless of its name)
  • The size of an empty file is given as 0 bytes

However, files and folders obviously have names, that must be stored somewhere.

  • Where, roughly, are they stored?
  • Is the maximum memory available to store these data a predefined number or is it dependent on the available space in disk?
  • Does an empty file with a short name take less space than an empty file with a larger name? (or perhaps the data structure in which these names are stored have a fixed byte count for each file, which perhaps fills the remaining bytes with \0?)
  • Does an empty folder with a short name take less space than an empty folder with a larger name?
  • Does an empty folder called foobar take less space, same space or more space than an empty file called foobar?
  • Does an empty file at /etc/empty.txt take less space, same space or more space than an empty file at /etc/long/nested/path/until/the/empty/file/is/reached/empty.txt?

Best Answer

File names are stored in the directory. A directory is composed of directory entries, and each directory entry contains a filename and the inode number for that file. The inode contains various metadata, such as the user id and group id owning the file, the time that the inode was last modified, etc. A file with a longer file name will take up more space in the directory. There can be multiple directory entries (in the same or different directories) that reference the same inode number. When an additional directory entry is created pointing to the same inode, it is referred to as creating hard link.

There is a fixed number of inodes in the inode table, so if you create a large number of inodes, you can eventually run out of space in the inode table. (You can see how many inodes are in use via "df -i". You can also create the file system with a large number of inodes, if you anticipate the average size of inodes in the file system to be smaller than the default.)

Directories are also composed of inodes, and work much like files, with the following exception. First, even an "empty" directory will have directory entries for '.' (the directory itself) and ".." (the parent directory), so even an "empty" directory will take up 4k of space. Secondly, a directory may not have hard links. That is (ignoring the '.' and '..' entries), there can only be directory entry referencing a directory inode. This means that directories form a tree, and not a generalized graph.