Simple answer: Because it's defined that way.
Longer answer: It's defined that way because some operations are conceptually simpler:
- If a file contains 20 letters "A", and you remove all "A"s, then the file will become 20 bytes shorter. The same operation on a file that consisted of just "AAAAAAAAAAAAAAAAAAAA" would have to deal with the special case of a vanishing file.
- More practically, deleting the last line of a text file would need to be special-cased.
- Text editors that regularly make a backup would need special-case code to deal with the situation that the user might delete the last line, go to lunch, then come back and add another line. Further complications arise if some other users created a file with that name in the mean time.
You can do more things:
* Error log files tend to be created empty, to be filled if and only if an error happens.
* To find out how many errors happened, you count the number of lines in the log files. If the log file is empty, the number of errors is zero, which makes perfect sense.
* Sometimes you see files where all the relevant text is in the file name, e.g. this-is-the-logging-directory
. This prevents overeager administrators from deleting empty directories after installation, and it also prevents bugs where a program or a user accidentally creates a file where the program would like to see a directory later. The git
program (and others) tend to ignore empty directories, and if a project/administrator/user wants to have a record that the directory exists even though it has no useful content (yet), you may see an empty file named empty
or empty.directory
.
No operations become more complicated:
- Concatenating files: this is just a no-op with an empty file.
- Searching for a string in a file: this is covered by the standard case of "if the file is shorter than the search term, it cannot contain the search term".
- Reading from the file: programs need to deal with hitting the end of the file before they got what they expected, so again the case of a zero-length file does not involve extra thinking for the programmer: he'll just hit end-of-file from the beginning.
In the case of files, the "there is a file recorded somewhere" aspect (inode and/or file name) comes on top of the above considerations, but file systems would not do that if empty files were useless.
In general, all of the above reasons except those related to file names apply to sequences.
Most notably to strings, which are sequences of characters: Zero-length strings are commonplace inside of programs.
String are usually disallowed at the user level if they don't make sense: a file name is a string, and most file systems do not allow an empty string as a file name; internally, when creating file names from fragments, the program may well have an empty string as one of the fragments.