[fpc-pascal] Adding a array of float in ressource and use it ?

Michael Van Canneyt michael at freepascal.org
Tue Mar 7 14:23:55 CET 2017



On Tue, 7 Mar 2017, Sven Barth via fpc-pascal wrote:

> Am 07.03.2017 13:49 schrieb "fredvs" <fiens at hotmail.com>:
>>
>>> To access a file stored as a resource you need to use TResourceStream.
>>
>> Ho my Dog, I did not know this one.
>> More than perfect, many thanks Sven.
>>
>> PS: About array of float into TFileStream, after Googling a while, it s
> not
>> possible to do directly like fpc does for C compilers.
>> You need a conversion (like explained by Lukasz Sokol).
>> And it is the reason why I am (once again) very impressed by fpc.
>
> Huh? Of course you can do that rather similary in C as well.

Indeed. You can do exactly the same. You can do this:

{$mode objfpc}
uses classes;


Type
   Float = Double;
   TFloatArray = Array of Float;

Procedure TestRW(X : TFloatArray);

Var
   F : TFileStream;
   Y : TFloatArray;
   I : Integer;

begin
   // Write
   F:=TFileStream.Create('float.dat',fmCreate);
   try
     F.WriteBuffer(X[0],Length(X)*SizeOf(Float));
   finally
     F.Free;
   end;
   // Read
   F:=TFileStream.Create('float.dat',fmOpenRead);
   try
     SetLength(Y,F.Size div SizeOf(Float));
     F.ReadBuffer(Y[0],F.Size);
   finally
     F.Free;
   end;
   // Check
   If Length(Y)<>Length(X) then
     Writeln('Wrong length')
   else For I:=0 to Length(X)-1 do
     if (X[i]<>Y[i]) then
       Writeln('Wrong element at pos ',i,': ',X[i]<>Y[i]);
end;

var
   X : TFloatArray;
   I : Integer;

begin
   SetLength(X,10);
   Writeln('Floats');
   For I:=0 to Length(X)-1 do
      X[i]:=10+(1/(1+I));
   TestRW(X);
   Writeln('integers');
   For I:=0 to Length(X)-1 do
      X[i]:=10+I;
   TestRW(X);
end.

Michael.



More information about the fpc-pascal mailing list