回复 #2 Passion 的帖子
报告LiuXiao老大:发现问题解决办法。
procedure TCnSourceDiffForm.DoOpenFile(OpenFile1: Boolean);
...
if Kind = fkDiskFile then // 存盘文件
Lines1.LoadFromFile(FileName) {此处不能直接LoadFromFile,应对非Ansi编码的文件进行转换处理}
...
以下是我的解决办法:
type
TTextFormat=(tfAnsi,tfUnicode,tfUnicodeBigEndian,tfUtf8);
const
TextFormatFlag:array[tfAnsi..tfUtf8] of word=($0000,$FFFE,$FEFF,$EFBB);
function WordLoHiExchange(w:Word):Word;register;
asm
XCHG AL, AH
end;
{ TextFormat返回文本编码类型,sText未经处理的文本 }
procedure ReadTextFile(const FileName: string; var TextFormat: TTextFormat; var sText:string);
var
w:Word;
b:Byte;
begin
with TFileStream.Create(FileName,fmOpenRead or fmShareDenyNone) do
try
Read(w,2);
w:=WordLoHiExchange(w);//因为是以Word数据类型读取,故高低字节互换
if w = TextFormatFlag[tfUnicode] then
TextFormat:= tfUnicode
else if w = TextFormatFlag[tfUnicodeBigEndian] then
TextFormat:= tfUnicodeBigEndian
else if w = TextFormatFlag[tfUtf8] then
begin
Read(b,1);//这里要注意一下,UFT-8必须要跳过三个字节。
TextFormat:=tfUtf8;
end else
begin
TextFormat:=tfANSI;
Position:=0;
end;
SetLength(sText,Size-Position);
ReadBuffer(sText[1],Size-Position);
finally
Free;
end;
end;
procedure TCnSourceDiffForm.DoOpenFile(OpenFile1: Boolean);
var
tff: TTextFormat;
sMemo: string;
...
if Kind = fkDiskFile then // 存盘文件
begin
//Lines1.LoadFromFile(FileName)
ReadTextFile(Self.dlgOpen1.FileName, tff, sMemo);
//
case tff of
tfAnsi: Lines1.Text:= sMemo;
tfUtf8: Lines1.Text:= Utf8ToAnsi(sMemo);
tfUnicode: Lines.Text:= WideCharToString(PWideChar(sMemo));
//tfUnicodeBigEndian: //暂时没有找到这种编码的转换方法
end;
end;
|