把文件映射到内存再转换
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
btnConvert: TButton;
btnOpenFile: TButton;
OpenDialog1: TOpenDialog;
procedure btnOpenFileClick(Sender: TObject);
procedure btnConvertClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
FileName:String;
FFileHandle: THandle
// Handle to the open file.
FMapHandle: THandle
// Handle to a file-mapping object
FFileSize: integer
// Variable to hold the file size.
FData: Pbyte
// Pointer to the file's data when mapped.
PData: byte;
Count:integer;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnOpenFileClick(Sender: TObject);
begin
if Opendialog1.Execute then
FileName:=Opendialog1.FileName
else
FileName:='';
end;
procedure TForm1.btnConvertClick(Sender: TObject);
var
ResultFile:TextFile;
Index:Integer;
TmpStr:char;
const
HexChars: PChar = '0123456789ABCDEF';
begin
if not FileExists(FileName) then
raise Exception.Create(文件不存在.')
else
FFileHandle := FileOpen(FileName, fmOpenReadWrite);
if FFileHandle = INVALID_HANDLE_VALUE then
raise Exception.Create('打开文件失败');
try
FFileSize := GetFileSize(FFileHandle, nil);
FMapHandle := CreateFileMapping(FFileHandle, nil,PAGE_READWRITE, 0, 0, nil);
if FMapHandle = 0 then
raise Exception.Create('创建文件映射对象失败');
finally
CloseHandle(FFileHandle);
end;
try
FData := MapViewOfFile(FMapHandle, FILE_MAP_ALL_ACCESS, 0, 0, FFileSize);
if FData = nil then
raise Exception.Create('映射文件视图到进程地址空间失败');
finally
CloseHandle(FMapHandle);
end;
if FData<>nil then
begin
try
AssignFile(ResultFile,'d:/Converted.txt');
ReWrite(ResultFile);
while count <= FFileSize - 1 do
begin
pdata := fdata^;
Index := (Pdata shr 4) and 15;
tmpStr:=HexChars[index];
Write(ResultFile,tmpStr);
Index:=Pdata and 15;
tmpStr:=HexChars[Index];
Write(ResultFile,tmpStr);
inc(fdata);
inc(count);
end;
finally
CloseFile(ResultFile);
showmessage('文件转换结束!');
end;
end;
end;
end.