你好,游客 登录 注册 搜索
背景:
阅读新闻

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

[日期:2016-09-22] 来源: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编码,但是并不是
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检测的并不一定是正确的字符集。

本文永久更新链接地址http://www.linuxidc.com/Linux/2016-09/135421.htm

linux
相关资讯       Linux file命令  file命令 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款