Domanda

Is there a way in Pascal to write to the start of a file, without overwriting other data?

I have learnt Seek(F, 0);but this overwrites the first thing in the file.

È stato utile?

Soluzione

You may achieve your goal with the following algorithm:

  • Create temporary file;
  • Write your new data to this temporary file;
  • Read all data from target file and append them to temporary file;
  • Rename temporary file to target one;

Altri suggerimenti

You cannot insert new data in front of existing data. Writing to the start/middle of a file always overwrites existing data, you cannot change that. Your only option is to create a new file, write your new data to it first, then append the contents of the existing file to the new file, then finally replace the existing file with the new file.

It is not possible to insert into a file. You can only overwrite or append. So if you want to do it yourself with a simple linear file then you need to re-write the entire file. If your file is large then this is rather unappealing.

One obvious way to solve your problem is to use a local database rather than writing your own file handling mechanisms. The database layer manages indexing for you so that you can avoid expensive entire file re-writes.

Of course, if your file is small and you don't care about performance then you solve your problem easily enough. This recipe shows how to insert a record into position i in the file. For your stated goal of inserting at the start then i would be zero.

  • Read then entire file into an array of N records.
  • Write the first i records back to the file.
  • Write the inserted record back to the file.
  • Write the remaining N-i original records back to the file.

A variant of this.

procedure InsertFile(const aFile, aLine: String);
var
  vList: TStringList;
begin
  vList:= TStringList.Create;
  try
    vList.LoadFromFile(aFile);
    vList.Insert(0, aLine);
    vList.SaveToFile(aFile);
  finally
    vList.Free;
  end;
end;

But with same limitations. For large files it will be slow as whole file is loaded in memory.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top