[fpc-pascal] How to append data to a file of byte?

Bo Berglund bo.berglund at gmail.com
Sun Oct 14 17:53:03 CEST 2018


On Sun, 14 Oct 2018 15:50:56 +0200 (CEST), in
gmane.comp.compilers.free-pascal.general you wrote:

>> This throws an error at SeekEof:
>>
>>  AssignFile(F, FileName);
>>  if AppendToFile then
>>    SeekEof(F)
>>  else
>>    Rewrite(F,1);
>>  BlockWrite(F, Buf[0], Length(Buf));
>>  CloseFile(F);
>
>Was the Seek() function punished by you ? :)
>
>https://www.freepascal.org/docs-html/rtl/system/seek.html

Yes, I looked at that too, but it requires me to supply the current
size of the file as the second argument....

What will happen if the file does not exist yet? Do I have to test for
that too or will the Reset/Rewrite calls handle this?

>Additionally, you must always open the file usng reset or rewrite. 
>SeekEOF (or Seek) when you didn't open the file first, is wrong.

Yes, I had not completed the code yet because of this issue with the
way to put the position at end of file...

>For appending to an existing untyped file, you must call reset(), then call Seek.
>

Now I have changed to this, and it compiles without errors. But I
can't test yet because oteher parts of the code supplying the data is
not ready...

  AssignFile(F, FileName);
  if AppendToFile then
  begin
    Reset(F, 1);
    Seek(F,FileSize(F)); // Does FileSize provide the size in bytes?
  end
  else
    Rewrite(F,1);
  BlockWrite(F, Buf[0], Length(Buf));
  CloseFile(F);

> In general, I would recommend using streams for binary IO.

I am pretty uncomfortable using streams. Don't really know how they
work...

(I am an old hand, started using Pascal on the Apple II, then T-Pascal
on IBM PC etc. That was back in the 1980:es...
Delphi since about 1995-96)


-- 
Bo Berglund
Developer in Sweden



More information about the fpc-pascal mailing list