Unicodeのファイルを読み込む
Unicodeのテキストファイルを読み込み、Shift-JISのテキストとして返す関数です。
DOSやWindowsの形式(Little Endian)用と、Big Endian用の二つがあります。ファイルがUnicodeかどうかを簡易的に判別するには、そのファイルの先頭2byteを調べて、$FFFEならLittle EndianのUnicode,$FEFFならBig EndianのUnicodeと判定します(この方法では、バイナリファイルの先頭が上記のいづれかの場合には当然誤作動があります)。
// Unicode(Little Endian)のファイルを読込みShift-Jisのテキストを返す
// ファイルの先頭2byteが$FFFEならLittle Endian
function LoadUniLi(const FileName: string): string;
var
Fs: TFileStream;
Sz: integer;
Pc: PChar;
begin
Result :='';
Fs := TFileStream.Create(FileName, fmOpenRead);
try
Fs.Position := 0;
sz := Fs.Size;
try
Pc := AllocMem(sz + 10);
Fs.Seek(0, soFromBeginning);
try
if Fs.Read(Pc^, sz) = sz then
begin
Result := WideCharToString(PWideChar(Pc+2));//先頭2byteをカット
end;
finally
FreeMem(Pc);
end;
except
raise Exception.Create('メモリを確保出来ませんでした.');
end;
finally
Fs.Free;
end;
end;
// Unicode(Big Endian)のファイルを読込みShift-Jisのテキストを返す
// ファイルの先頭2byteが$FEFFならLittle Endian
function LoadUniBi(const FileName: string): string;
var
Fs: TFileStream;
Sz, n: integer;
Pc: PChar;
Tc: char;
begin
Result := '';
Fs := TFileStream.Create(FIleName, fmOpenRead);
try
Fs.Position := 0;
sz := Fs.Size;
try
Pc := AllocMem(sz + 10);
Fs.Seek(0, soFromBeginning);
try
if Fs.Read(Pc^, sz) = sz then
begin
n := 0;
// WordのLow, Highを入替える(何て原始的な方法)
while n < sz do
begin
Tc := (Pc+n)^;
(Pc+n)^ := (Pc+n+1)^;
(Pc+n+1)^ := Tc;
Inc(n, 2);
end;
Result := WideCharToString(PWideChar(Pc+2));//先頭2byteをカット
end;
finally
FreeMem(Pc);
end;
except
raise Exception.Create('メモリを確保出来ませんでした.');
end;
finally
Fs.Free;
end;
end;
このユニットの使用は改変や一部流用も含めて自由です。