delphi获取文件编码

//delphi获取文件编码
unit EncodeUnit;

interface

uses
   SysUtils, Windows, Classes;

type
   TTextFormat = ( tfAnsi, tfUnicode, tfUnicodeBigEndian, tfUtf8 );

const
   TextFormatFlag: array [tfAnsi..tfUtf8] of Word = ( $0000,$FFFE,$FEFF,$EFBB );

   function GetFileEncodeing(const FileName: string): TTextFormat;
   function WideStringToString(const WS: WideString; CodePage: Word): string;

implementation

//高低字节互换
function WordLoHiExchange(w: Word): Word; register;
asm
   XCHG AL, AH
end;

//取得文件编码
function GetFileEncodeing(const FileName: string): TTextFormat;
var
   W: Word;
begin
   try
     with TFileStream.Create(FileName,fmOpenRead or fmShareDenyNone) do
     begin
       Seek(0, soFromBeginning);
       Read(W,2);
       W := WordLoHiExchange(W); //因为是以Word数据类型读取,故高低字节互换
       if W=TextFormatFlag[tfUnicode] then
         Result := tfUnicode
       else if W=TextFormatFlag[tfUnicodeBigEndian] then
         Result := tfUnicodeBigEndian
       else if W=TextFormatFlag[tfUtf8] then
         Result := tfUtf8
       else
         Result := tfAnsi;
       Free;
     end;
   except
     Result := tfAnsi;
   end;
end;

//Unicode 转 ANSI
function WideStringToString(const WS: WideString; CodePage: Word): string;
var
   InputLength, OutputLength: Integer;
begin
   InputLength := Length(WS);
   OutputLength := WideCharToMultiByte(CodePage, 0, PWideChar(WS), InputLength, nil, 0, nil, nil);
   SetLength(Result, OutputLength);
   WideCharToMultiByte(CodePage, 0, PWideChar(WS), InputLength, PAnsiChar(Result), OutputLength, nil, nil);
end;

end.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值