24 Votes

Lazarus: Load File as Byte Array and save Byte Array as File

Tutorial by Stefan Trost | Last update on 2023-02-18 | Created on 2018-01-01

In this tutorial I want to show you how to read a file byte by byte into an array as well as how to write a byte array back into a file again.

First of all, we define a byte array that we need for both processes respectively directions:

type
  TByteArr = array of Byte;

We can now fill it with some individual bytes, for example in the following way:

var
  BA: TByteArr;
begin
  SetLength(BA, 3);
  BA[0] := 65;
  BA[1] := $41;
  BA[2] := %1000001;

When doing so, it does not matter whether we specify the bytes in decimal, hexadecimal, or binary notation or whether we get them from a function like ord(), for example. The sample code shows each of these four possibilities.

65 is the ASCII code for "A". In hexadecimal notation the number 65 corresponds to 41 and in binary notation to 1000001. Also ord('A') gives us the ASCII value 65 for "A".

Accordingly, in the example, we set all four bytes of the array to the same value. Decimal values can be written into the code as simple integer numbers while hexadecimal values are to be marked with $ and binary numbers with %. This way the compiler can distinguish which number we mean.

Save Byte Array

Now let's see how we can save our byte array to a file. For this we use the following procedure, which we can pass a byte array and our desired file name for storage:

procedure SaveByteArray(AByteArray: TByteArr; const AFileName: string);
var
  AStream: TStream;
begin

  if FileExistsUTF8(AFileName) then DeleteFileUTF8(AFileName);

  AStream := TFileStreamUTF8.Create(AFileName, fmCreate);
  try
     AStream.WriteBuffer(Pointer(AByteArray)^, Length(AByteArray));
  finally
     AStream.Free;
  end;

end;  

First of all, we check whether a file with the specified name already exists and delete it if so. Alternatively, we could of course also ask the user before deleting the existing file, but here we would like to limit ourselves to the essentials. Then we create a FileStream and write the array in its entire length into it. With this, the byte array is saved.

A usage example may look like this:

var
  BA: TByteArr;
begin
  SetLength(BA, 1);
  BA[0] := 65;
  SaveByteArray(BA, 'file.dat');

Here we first create a byte array consisting of two elements and then we use the procedure just presented for storage. As the first parameter we pass our byte array to the procedure, as second parameter the desired file name.

Load Byte Array

Now we want to see the reverse path as well. To load a file from the hard disk into a byte array, the following function can be used, to which we can pass a file name as a parameter:

function LoadByteArray(const AFileName: string): TByteArr;
var
  AStream: TStream;
  ADataLeft: Integer;
begin
  SetLength(result, 0);

  if not FileExistsUTF8(AFileName) then exit;

  AStream := TFileStreamUTF8.Create(AFileName, fmOpenRead or fmShareDenyWrite);
  try
     AStream.Position := 0;
     ADataLeft := AStream.Size;
     SetLength(result, ADataLeft div SizeOf(Byte));
     AStream.Read(PByte(result)^, ADataLeft);
  finally
     AStream.Free;
  end;

end; 

Also in this procedure, we first check whether a file exists under the specified file name and terminate if not. Previously, we already set the result to a length of 0, so the function returns an empty array in this case. If the file exists, we also create a FileStream in this function, which we use to read all the bytes of the file into our result byte array.

A call to the function may look like this:

var
  BA: TByteArr;
begin
  BA := LoadByteArray('file.dat');

We only pass a file name as parameter and get back the byte array consisting of the bytes of the requested file.

Visualize Byte Array

When working with byte arrays, sooner or later the question of displaying the content of the byte array comes up. It makes sense to output the byte arrays in hexadecimal form as a string. For example, an output of the byte array mentioned above would look like this: "41 41 41 41".

ReplyPositiveNegative

About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.