红联Linux门户
Linux帮助

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

发布时间:2016-09-27 10:51:30来源:linux网站作者:gaopengtttt
今天在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;
}
 
实际上并没有什么不同这两个文件 test10 和test11 都有2行其中一个很长的行全部是test字符串,第二行是Linux。
明显他们应该返回UTF8编码,但是并不是。
linux@linux:~$ file -i test10.txt
test10.txt: text/plain; charset=us-ascii
linux@linux:~$ file -i test11.txt
test11.txt: text/plain; charset=utf-8
 
可以看到如果"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检测的并不一定是正确的字符集。
 
本文永久更新地址:http://www.linuxdiyf.com/linux/24527.html