关于Linux file命令是如何判断文件字符集的

今天在Linux使用file -i 查看MYSQLDUMP文件的时候其输出为

charset=us-ascii with very long lines

我导出的文件应该是utf8的,为什么会显示ASCII呢,我们知道ASCII并没有中文编码,那么真的有问题吗?

然后用如下2个小程序测试了一下

#include<stdio.h>

int main(void)
{
        FILE *p;
        int i=0;
        p=fopen("test11.txt","w+");
        fputs("Linux公社\n",p);
        while(i<50000000)
        {
                fputs("test",p);
                i++;
        }

        fputs("\n",p);
        fclose(p);
        return 0;
}

-------------------------------------------------------


#include<stdio.h>

int main(void)
{
        FILE *p;
        int i=0;
        p=fopen("test10.txt","w+");
        while(i<50000000)
        {
                fputs("test",p);
                i++;
        }

        fputs("\n",p);
        fputs("Linux公社\n",p);
        fclose(p);
        return 0;
}

可以看到如果"Linux公社"字符串在第二行返回为ASCII而在第一行为UTF-8,我们可以推测出 file 命令是检测文件开头的某些字符而返回的,并没有全部查看,或者有什么其他算法,但是他不是全部查看。试想如果全部查看一遍 一个200G的备份文件瞬间就返回了结果也是不可能的。
在file的帮助中也明确的写着
  Once file has determined the character set used in a text-type file, it will attempt to determine in what language the file is written.  The language tests
    look for particular strings (cf.  ) that can appear anywhere in the first few blocks of a file.

当然要知道具体的方法估计只有源码。

所以file -i检测的并不一定是正确的字符集。

猜你喜欢

转载自www.linuxidc.com/Linux/2016-09/135421.htm