Write to middle of text file

1.2k Views Asked by At

I am using Delphi 7.0 and need to be able to write to the middle of a text file. Here is an example of the text file my program creates.

~V

VERS.  2.0: CWLS LOG ASCII STANDARD - VERSION 2.0

WRAP.  NO : One line per depth step

~W

STRT.Ft 10000 : Start Depth

STOP.Ft  11995 : Stop Depth

STEP.Ft 5 : Step

... A bunch of data follows.

Now, when I initially write the values to the text file I would like to remember the file position of the STOP value of 11995 in the above example. Now, some time later my data will change and I would like to move to the position of 11995 and write the new stop value. That way I don't need to rewrite everything in the file.

1

There are 1 best solutions below

0
On BEST ANSWER

With standard Pascal File I/O you can only read, rewrite or append data in the file.
If you want to change data in a certain position of the file you can use TFileStream:

var
  f:TFileStream;
  PositionStr:String;
  PositionValue:Integer;
begin
  f := TFileStream.Create('filename.log',fmOpenReadWrite);
  PositionValue := 200000; // new STOP Position 
  PositionStr := IntToStr(PositionValue);
  f.Seek(100,soFromBeginning); // Data will be overwritten from position 100
  f.WriteBuffer(PositionStr[1], length(PositionStr));
  f.free;
end;