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.

相关阅读 >>

Delphi 10.4.1的编译器bug终于修正了!

Delphi中执行javascript代码

Delphi 2009 泛型容器单元(generics.collections)[5]: tobject...<t> 系列

Delphi跨平台tcp库的封装

Delphi2010的操作界面切换到Delphi7的操作模式

Delphi实现webservice带身份认证的数据传输

Delphi 执行一个外部程序,当外部程序结束后言主程序立即响应

Delphi windows 编程[2] - 学习窗体生成的过程二

移植Delphi7的tclientsocket,tserversocket

Delphi命令行窗口实现9*9乘法表

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...