Delphi rewrites one line

Is it possible to overwrite one line of a text file and then save and close it?

For example, I need to rewrite the first line and keep all the rest. Is there a function to do this or do I need to copy the whole file after one line change?

My file contains more thausand lines and I only need to change the first line.

Example file:

test;test1;test2
other;other;other
other;other;other
x1000

      

and then

something;something;something
other;other;other
other;other;other
x1000

      

See what I mean? I just want to save my file as if it is only changing the first line. I could copy the entire file and paste it after I changed the first line, but I'm wondering if there is a method already included in delphi to only change a specific line in a text file. Thank!

+3


source to share


2 answers


It's impossible. Files are stored linearly and do not support insertion. If your string was fixed, you can overwrite it. However, you want to replace the string with new content that is larger. It's impossible. You will need to overwrite the entire file.



A database may be more suitable for your needs than a text file.

+6


source


I think the easiest way here is to use TStringList this way:

procedure InPlaceFileEdit(fFile : String);
begin
F:=TStringList.Create;
try
  F.LoadFromFile(fFile);
  F.Strings[0]:='something;something;something' ;// Change the contents of the first line
  F.SaveToFile(fFile);
finally
 F.Free
end
end;

      



Of course, this is a trick that rewrites the file completely every time.

+2


source







All Articles