详解file命令判断文件类型的逻辑

1. 引入

在linux系统上,file命令是用于检测文件类型的最好的工具,性能也一流。它能检测elf、pdf等各种各样的文件类型。

那么,问题来了,file命令是如何检测文件类型的呢?这个问题用中文、英文在bing和google搜索得到的都是file的用法,没有回答它的原理。

那本文简述如何查看file命令的原理的过程。

2. 如何理解file并找到源码

  1. 用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: 根据变成语言关键字来匹配(不准,详见下节描述)
  1. 用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. 源码解读

  1. 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值