获取txt文本文档的编码类型(c++,c#)

本文介绍了一种通过检查文件头部特定字节序列来判断文本文件编码格式的方法,支持UTF-8、Unicode及其变体等常见编码,并提供了C++及C#实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件的字符集在Windows下有两种,一种是ANSI,一种Unicode。

对于Unicode,Windows支持了它的三种编码方式,一种是小尾编码(Unicode),一种是大尾编码(BigEndianUnicode),一种是UTF-8编码。

我们可以从文件的头部来区分一个文件是属于哪种编码。当头部开始的两个字节为 FF FE时,是Unicode的小尾编码;当头部的两个字节为FE FF时,是Unicode的大尾编码;当头部两个字节为EF BB时,是Unicode的UTF-8编码;当它不为这些时,则是ANSI编码。


在项目中正好用到判断编码的函数,写了一个辅助函数如下:

/***********************************************
书写人  : zhichao.wang
函数类型: 辅助函数
函数名称: lcl_GetTextEncode
函数功能: 获取指定路径的txt文档的编码格式
返回值  : LONG  
            1 - UTF-8
            2 - Unicode
            3 - Unicode big endian
            4 - ASCII
           -1 - error
***********************************************/
LONG CNsoControl::lcl_GetTextEncode(CString strTxtPath)
{
    LONG nType = -1;//error
    //打开要判断的文件
    FILE *pFile = NULL;  
    errno_t dError = _wfopen_s(&pFile,strTxtPath,L"r");  
    if ( 0 != dError )  
    {  
        fclose(pFile);
        return nType;  
    }  
    //这里要注意是用unsigned   char,不然的话读取到的数据会因为溢出而无法正确判断
    unsigned   char*   chFileFlag   =   new   unsigned   char[3];
    fread(chFileFlag,   1,   3,   pFile);

    if(chFileFlag[0]   ==   0xEF   &&   chFileFlag[1]   ==   0xBB   &&   chFileFlag[2]   ==   0xBF)
        nType = 1;//UTF-8
    else if (chFileFlag[0]   ==   0xFF   &&   chFileFlag[1]   ==   0xFE)
        nType = 2;//Unicode
    else if (chFileFlag[0]   ==   0xFE   &&   chFileFlag[1]   ==   0xFF)
        nType = 3;//Unicode big endian text
    else  
        nType = 4;//ASCII
    fclose(pFile);
    delete chFileFlag;
    return nType;   
}

c#代码如下:

public System.Text.Encoding  GetFileEncodeType(string filename)
{
    System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
    System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
    Byte[] buffer = br.ReadBytes(2);
    if(buffer[0]>=0xEF)
    {
        if(buffer[0]==0xEF && buffer[1]==0xBB)
        {
             return System.Text.Encoding.UTF8;
        }
        else if(buffer[0]==0xFE && buffer[1]==0xFF)
        {
             return System.Text.Encoding.BigEndianUnicode;
        }
        else if(buffer[0]==0xFF && buffer[1]==0xFE)
        {
             return System.Text.Encoding.Unicode;
        }
        else
        {
             return System.Text.Encoding.Default;
        }
    }
    else
    {
             return System.Text.Encoding.Default;
    }
}

程序中System.Text.Encoding.Default是指操作系统的当前 ANSI 代码页的编码。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值