I was reading about the file
command and I came across something I don't quite understand:
file is designed to determine the kind of file being queried.... file accomplishes this by performing three sets of tests on the file in question:
- filesystem tests,
- magic tests,
- language tests
What are magic tests?
2 Answers 2
"magic" here refers to "magic numbers": a special value that's in a known place in a file that identifies its type. The file
command has a database of these numbers and what type they correspond to. The library that goes with that database is called libmagic, and you can access that from your own programs.
They aren't necessarily "numbers" as we might think of them. For example, a PNG image file always starts with "\x89PNG\r\n\x1a\n", a Java class begins with the four bytes (in hexadecimal) CA FE BA BE, and an HTML file has "< html" somewhere near the start. It's just some small sequence of data that's known to be in a file of that type, usually very close to the start.
When people are defining file formats they often include one of these in it either deliberately or just as part of making the format fit together. file
can use them afterwards. It also has other ways of actually looking at the contents of the file to guess what it is ("language tests").
-
6Note that originally, the "magic numbers" were, specifically, the first two bytes of an executable file, used by the kernel to load it in the appropriate way.
#!
is actually an example of this, because the kernel itself, on seeing those bytes, is supposed to invoke the command that follows.IMSoP– IMSoP2014年06月22日 00:05:43 +00:00Commented Jun 22, 2014 at 0:05
That refers to the "magic bytes" which many file formats have at the beginning of a file which show what kind of file this is.
E.g. if a file starts with #!
then it is considered a script.
-
Who writes these "magic bytes" in the file?Antonios Sarikas– Antonios Sarikas2024年12月26日 19:34:36 +00:00Commented Dec 26, 2024 at 19:34
-
@AntoniosSarikas The application which creates the file. Or the user, manually, e.g. when creating a shell script with an editor.Hauke Laging– Hauke Laging2024年12月27日 00:22:10 +00:00Commented Dec 27, 2024 at 0:22
You must log in to answer this question.
Explore related questions
See similar questions with these tags.