2

in visual basic i can open a binary(exe) file with below way :

Strx$ = Space(FileLen(FileName))
Open FileName For Binary As #1
  Get #1, , Strx$
Close

in this way i can read all of binary file characters and read file content like this format :

alt text
(source: iranblog.com)

and the question is how can i open a binary(exe) file in delphi with a string format(Like image) and not 0,1(binary) format ?

Thank you!

2
  • 2
    What exactly do you want to do? Maybe we can suggest something better, because opening a binary file as text will most likely solve nothing. Commented Jul 16, 2010 at 9:04
  • A more common way to do this would be to use a hex viewer/editor component rather than just dumping stuff to the screen which is not readable. Commented Jul 20, 2010 at 20:14

2 Answers 2

6

EXE files contain embedded NULL (#0) Characters. You may have problems using Strings as typically NULL is found at the end of the string. Some routines will stop working with a string once the NULL is encountered.

Having said that the following would get the contents of a file into a string.

function GetFileIntoString(FileName : String) : String;
var
 SS : TStringStream;
begin
  SS := TStringStream.Create('');   
  try
    SS.LoadFromFile(FileName);
    result := SS.DataString;
  finally
    SS.Free;
  end;
end;
Sign up to request clarification or add additional context in comments.

6 Comments

memory leak -- you should use try/finally and .free your stringStream
does it work with Delphi 2009 and higher too? (thinking of Unicode and default character encodings ...)
Leak Fixed. In Delphi 2009 the string will be Unicode, and prior it will be Ansi. Both will load the file into the string.
See forums.codegear.com/thread.jspa?threadID=31135&tstart=42 - in Delphi 2009+ TStringStream is a stream of bytes (not a stream of characters), which is fine, but accessing the DataString will process the raw bytes through the TEncoding class, which is not known in this code example.
@mjustin is right. In D2009+, accessing the DataString will corrupt the bytes, unless you assign an 8-bit clean TEncoding object to the stream. Better to use TMemoryStream instead. Even better, use a memory mapping instead, then you do not have to read the file bytes into a separate memory block at all.
|
1

Here are some good resources with examples.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.