读取ASNI/UTF8/UNICODE/UNICODE Big格式文件的通用函数

函数在Delphi2007和Delphi6中测试通过。

 

function LoadTextFile(Filename: String): String; var Stream:TMemoryStream; Flag: String; WS: WideString; CodeType: Byte; //0:ANSI,1:UTF-8,2:Unicode,3:Unicode big procedure ProcessUnicodeBig; var i: integer; n: Word; begin for i := 1 to Length(WS) do begin n := Word(WS[i]); asm mov ax, n xchg ah, al mov n, ax end; WS[i] := WideChar(n); end; end; begin Result := ''; CodeType := 0; Stream := TMemoryStream.Create; try Stream.LoadFromFile(Filename); SetLength(Flag,3); Stream.Read(Flag[1],3); if Flag=#EF#BB#BF then CodeType := 1 else if (Flag[1]=#FF) and (Flag[2]=#FE) then CodeType := 2 else if (Flag[1]=#FE) and (Flag[2]=#FF) then CodeType := 3; case CodeType of 2,3: begin Stream.Seek(2, soFromBeginning); SetLength(WS,(Stream.Size-2) div 2); Stream.Read(WS[1],Stream.Size-2); if CodeType = 3 then ProcessUnicodeBig; Result := AnsiString(WS); end; 0: begin Stream.Seek(0, soFromBeginning); SetLength(Result, Stream.Size); Stream.Read(Result[1], Stream.Size); end; 1: begin Stream.Seek(3, soFromBeginning); SetLength(Result, Stream.Size-3); Stream.Read(Result[1], Stream.Size-3); Result := Utf8ToAnsi(Result); end; end; finally Stream.Free; end; end;  

你可能感兴趣的:(String,function,Stream,Integer,byte,Delphi)