歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> 關於Linux file命令是如何判斷文件字符集的

關於Linux file命令是如何判斷文件字符集的

日期:2017/2/28 13:48:45   编辑:Linux教程

今天在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編碼,但是並不是
linuxidc@linuxidc:~$ file -i test10.txt
test10.txt: text/plain; charset=us-ascii
linuxidc@linuxidc:~$ 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檢測的並不一定是正確的字符集。

Copyright © Linux教程網 All Rights Reserved