判断文件的编码格式(Unicode;Utf-8;Ansi;Unicode Big Endian)

来源:岁月联盟 编辑:exp 时间:2012-08-21
程序原理通过通过判断文件头几个字节来判断文件的编码格式

ANSI :         无格式定义;
Unicode :      前两个字节为 FFFE ;
Unicode big endian : 前两字节为 FEFF ; 
UTF-8 :        前两字节为 EFBB ;

代码部分来自网络+自己修改
定义:

type
  TTextFormat = (tfAnsi, tfUnicode, tfUnicodeBigEndian, tfUtf8);
end;
const
  TextFormatFlag: array [tfAnsi .. tfUtf8] of word = ($0000, $FFFE, $FEFF,
    $EFBB);

函数
function GetFileType(const FileName: string): TTextFormat;
var
  w: word;
  b: Byte;
begin
  with TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone) do
    try
      Read(w, 2);
      asm    // 因为是以Word数据类型读取,故高低字节互换
          PUSH EAX
          MOVZX EAX,  w
          XCHG AL,AH
          MOV w, AX
          POP EAX
        end;      
       if w = TextFormatFlag[tfUnicode] then
        Result := TTextFormat.tfUnicode
      else if w = TextFormatFlag[tfUnicodeBigEndian] then
        Result := TTextFormat.tfUnicodeBigEndian
      else if w = TextFormatFlag[tfUtf8] then
        Result := TTextFormat.tfUtf8
      else
        Result := TTextFormat.tfAnsi;
    finally
      Free;
    end;
end; 

图片内容