1. 引入
在linux系统上,file命令是用于检测文件类型的最好的工具,性能也一流。它能检测elf、pdf等各种各样的文件类型。
那么,问题来了,file命令是如何检测文件类型的呢?这个问题用中文、英文在bing和google搜索得到的都是file的用法,没有回答它的原理。
那本文简述如何查看file命令的原理的过程。
2. 如何理解file并找到源码
- 用man命令查看file的专业说明
man能查看到linux命令的细节的最专业的文档,其中也会给出很多源码级别的描述。
file tests each argument in an attempt to classify it. There are three sets of tests, performed in this order: filesystem tests, magic tests, and language tests. The first test that succeeds causes the file type to be printed.
从中可以看到,file命令用三种方法来检测文件类型:
- filesystem tests:文件系统测试
- magic tests: magic code
- language tests: 根据变成语言关键字来匹配(不准,详见下节描述)
- 用man命令找到file的源码
滚动到man file的最后输出,可以看到:
AVAILABILITY
You can obtain the original author's latest version by anonymous FTP on ftp.astron.com in the directory /pub/file/file-X.YZ.tar.gz.
用浏览器打开如下链接,就能下载到file命令的最新源码
- http://ftp.astron.com/pub/file/
3. 源码解读
- filesystem tests
(1)首先,根据man的描述,发现这个和<sys/stat.h>有关,所以通过搜索引擎G先找到stat.h的源码:
https://pubs.opengroup.org/onlinepubs/7908799/xsh/sysstat.h.html
(2)发现 <sys/stat.h> 中关于类型的描述,如下:
S_IFMT
type of file
S_IFBLK
block special
S_IF