读书人

关于二进制文件操作的有关问题

发布时间: 2012-03-23 12:06:21 作者: rapoo

关于二进制文件操作的问题
我想写一个以二进制从文件读取数据,然后存入一个文本文件的程序,但是现在出现问题,一个300K的dll文件我读到richedit里,存到文本发现变成1.1M了,下面是读文件显示的代码,高手看看有什么问题。或者谁有例子给一个也行
var
F: file;
i, aByte: Byte;
aString: string;
begin
if FileExists(Edit1.Text) then
begin
Button1.Enabled := False;
Screen.Cursor := crHourGlass;
RichEdit1.Lines.Clear;
AssignFile(F, Edit1.Text);
ReSet(F, 1);
try
i := 0;
while not Eof(F) do
begin
BlockRead(F, aByte, 1);
if i = 255 then
begin
RichEdit1.Lines.Add(aString + '+ ');
i := 0;
end;
if i = 0 then
aString := ' ';
aString := aString + '# ' + IntToStr(aByte);
i := i + 1;
end;
if i > 0 then
RichEdit1.Lines.Add(aString + '; ')
else
if FileSize(F) > 0 then
(PChar(RichEdit1.Text) + Length(PChar(RichEdit1.Text)) - 1)^ := '; ';
finally
CloseFile(F);
end;
Screen.Cursor := crDefault;
Button1.Enabled := True;
end
else
ShowMessage( 'File not found! ');
end;

[解决办法]
帮顶下.
[解决办法]
肯定会变大,因为每一个Byte前你都加了一个#

Byte类型转换成String时,长度也会增加
例如 255 Btye类型 长度: 1 字节
'255 ' String类型 长度: 3 字节

[解决办法]
如果你想直接打开txt来看,没办法,只有用这样做。
如果通过你做的程序打开的话,可以压缩存储,打开的时候解压。
或者根本不转成txt,直接打开DLL然后转换显示
[解决办法]
你的办法是可以的。也可以用这个方法把一个可执行程序文件转成长字符串存入数据库中。
------解决方案--------------------


请问,什么叫“二进制文件”???
[解决办法]
function TForm1.GetChars(aHexStr: string): string;
var
i: Integer;
begin
aHexStr := StringReplace(aHexStr, ' ', ' ', [rfReplaceAll, rfIgnoreCase]);
for i := 1 to Length(aHexStr) do
begin
if Odd(i) then
begin
Result := Result + Char(StrToIntDef( '$ ' + Copy(aHexStr, i, 2), 0));
end;
end;
end;
[解决办法]
procedure ReadFileToBuffer(filename:string);
var
i:integer;
s:string;
begin
assignfile(F , filename);
reset(f , 1);
try
size:=FileSize(F);
getmem(buf , size+1);
BlockRead(F , buf^ ,size);
for i:=0 to size do
begin
s:=s+ ' '+inttohex(ord(buf[i]),2);
//if (inttohex(ord(buf[i]),2)= 'aa ') or (inttohex(ord(buf[i]),2)= 'AA ') then
//buf[i]:=#0;
end;
form1.memo1.Lines.Add(s);
assignfile(F1 , '1.dat ');
Rewrite(f1, 1);
BlockWrite(f1 , buf^ , size);
buf[size]:=#0;
finally
closefile(f);
closefile(f1);
end;
end;
[解决办法]
const data = '#77#90#80#0#2#0#0#0#4#0#15#0#255#255#0#0#184#0#0#0#0#0#0#0#64#0#153 ';

var
i, pos: integer;
bData: byte;
begin
pos := 0;

// 扫描data,挨个把 '#123 '形式的字符串转换成byte型数据
for i:=1 to Lenth(data) do
begin
if data[i]= '# ' then
begin
// 如果pos已经指向了一个 '# '则转换pos所指向的 '#123 '中的数字串为byte数据
if pos <> 0 and data[pos]= '# ' then
begin
bData := StrToInt( Copy(data, pos+1, i-pos-1) );
WriteByteToFile( bData ); // 把转换数据写入文件
end;
pos := i; // pos指向新的一个 '# '开头的数字串
end;
end;

// 转换最末尾一个 '#153 '
if i> pos and pos <> 0 and data[pos]= '# ' then
begin
bData := StrToInt( Copy(data, pos+1, i-pos) );
WriteByteToFile( bData );
end;
end;

读书人网 >.NET

热点推荐