soulbrother
soulbrother

Reputation: 57

delphi insert text into textfile at specific point

i want to edit a textfile. if i read a special line (let us say //--begin editing text here--//) then after this line i want to insert several lines but i don't want to override existing lines. is this possible with delphi? thanks!

sample text:

this

is a file

with text in it

//--begin inserting text here--//

and nothing in between

sample text after edit:

this

is a file

with text in it

//--begin inserting text here--//

now there is something

in between

and nothing in between

Upvotes: 3

Views: 11464

Answers (2)

Robert Love
Robert Love

Reputation: 12581

There are several ways you can do this.

The simplest version:

var 
  sl : TStringList;
  I : Integer;
begin
  sl := TStringList.Create;
  sl.LoadFromFile();
  // No you have an array of strings in memory one for each line
  for I := 0 to SL.Count -1 do
  begin
     sl.strings[I]; 
   end;
  sl.SaveToFile();
end;

You can also use other File IO Commands such as: To Read a text file:

  var
   t : TextFile;
  begin
    AssignFile(t,'FileName.txt');
    Reset(T);
    while not eof(t);
    begin
      Readln(T,LineOfText);
    end;
    CloseFile(T);
  end;

The to write out what you want..

  var
   t : TextFile;
  begin
    AssignFile(t,'FileName.txt');
    Rewrite(T);
    Writeln(T,LineOfText);
    Writeln(T,LineOfText);
    Writeln(T,LineOfText);
    CloseFile(T);
  end;

It should be noted that in reality both of the above methods are actually just rewriting the entire contents of the file.

The TFileStream class allows you manipulate the actual bytes of a file. In general you would need to read until you found the expected text. Then read ahead and cache the rest of the file, as you write out the new ending of the file.

Upvotes: 3

Roman Yankovsky
Roman Yankovsky

Reputation: 1217

var
  SL: TStringList;
  InsTextPos: Integer;
begin
  SL := TStringList.Create;
  try
    SL.LoadFromFile('c:\test.txt');
    InsTextPos := SL.IndexOf('//--begin inserting text here--//');
    if InsTextPos >= 0 then
    begin
      SL.Insert(InsTextPos+1, 'Inserting Line 2');
      SL.Insert(InsTextPos+1, 'Inserting Line 1');
      SL.SaveToFile('c:\test.txt');
    end;
  finally
    SL.Free;
  end;
end;

Upvotes: 8

Related Questions