//----------------------------------------------
// Unit Name: FileExt.pas
// Comment: 读写UTF8和UNICODE格式文件的一组函数
//----------------------------------------------
unit FileExt;
interface
uses SysUtils,Windows,Types,Classes;
const
utf8Head: Array[0..2] of Char = (#239,#$bb,#$bf);
unicodeHead: Array[0..1] of Char = (#255,#$fe);
function ReadUtf8File(const filename:string):UTF8String;
procedure WriteUtf8File(const filename:string;mem:Utf8String);
function ReadUnicodeFile(const filename:string):WideString;
procedure WriteUnicodeFile(const filename:string;mem:Widestring);
implementation
// read utf8 file
function ReadUtf8File(const filename:string):Utf8String;
var
memoStream:TFileStream;
buf:array of Char;
begin
memoStream:=TFileStream.Create(filename, fmOpenRead);
try
setlength(buf,memoStream.size);
memoStream.ReadBuffer(buf[0], memoStream.size);
//utf-8 file
if (buf[0]=Utf8Head[0]) and (buf[1]=Utf8Head[1]) and (buf[2]=Utf8Head[2]) then
begin
FillChar(buf, SizeOf(buf), #0);
memoStream.Seek(3,soFromBeginning);
setlength(buf,memoStream.size-3);
memoStream.ReadBuffer(buf[0], memoStream.size-3);
result:=Utf8String(buf);
exit;
end else result:=UTF8Encode(WideString('文件不是UTF8格式!'));
finally
memoStream.Free;
end;
end;
// read unicode file
function ReadUnicodeFile(const filename:string):WideString;
var
memoStream:TFileStream;
buf:array of Char;
begin
memoStream:=TFileStream.Create(filename, fmOpenRead);
try
setlength(buf,memoStream.size);
memoStream.ReadBuffer(buf[0], memoStream.size);
//unicode file
if (buf[0]=UnicodeHead[0]) and (buf[1]=UnicodeHead[1]) then
begin
FillChar(buf, SizeOf(buf), #0);
memoStream.Seek(2,soFromBeginning);
setlength(buf,memoStream.size-2);
memoStream.ReadBuffer(buf[0], memoStream.size-2);
result:=PWideChar(buf);
exit;
end else result:=WideString('文件不是UNICODE格式!');
finally
memoStream.Free;
end;
end;
procedure WriteUnicodeFile(const filename:string;mem:Widestring);
var
wms:TMemoryStream;
begin
wms:=TMemoryStream.Create;
wms.WriteBuffer(unicodeHead,length(unicodeHead));
wms.WriteBuffer(PChar(mem)^,length(mem)*2);
wms.SaveToFile(filename);
wms.Free;
end;
procedure WriteUtf8File(const filename:string;mem:Utf8String);
var
wms:TMemoryStream;
begin
wms:=TMemoryStream.Create;
wms.WriteBuffer(utf8Head,length(utf8Head));
wms.WriteBuffer(pchar(mem)^,length(Ansistring(mem)));
wms.SaveToFile(filename);
wms.Free;
end;
end.