How operate on TFileStream

Błażej picture Błażej · Dec 12, 2011 · Viewed 10.3k times · Source

Hello recently I replace TextFile with TFileStream. I never use it so I have small problem with it.

  • How can I add someting to my file after I assign it to variable?
  • How can I read someting form that file?

I need defined line form that file so I was doing something like that:

var linia_klienta:array[0..30] of string;
AssignFile(tempPlik,'klienci.txt');
Reset(tempPlik);
i:=0;
While Not Eof(tempPlik) do
  begin
    Readln(tempPlik,linia_klient[i]);
    inc(i);
  end;
CloseFile(tempPlik);

Then when line two is needed I simply

edit1.text = linia_klienta[1];

Answer

RRUZ picture RRUZ · Dec 12, 2011

If you need to read a text file and access each line, try instead using a TStringList class with this class you can load a file, read the data (accesing each line using a index) and save the data back.

something like this

FText  : TStringList;
i : integer;
begin
 FText := TStringList.Create;
 try
  FText.LoadFromFile('C:\Foo\Foo.txt');

    //read the lines
    for i:=0 to FText.Count-1 do    
     ProcessLine(FText[i]);  //do something   

  //Add additional lines
  FText.Add('Adding a new line to the end');
  FText.Add('Adding a new line to the end');    

  //Save the data back
  FText.SaveToFile('C:\Foo\Foo.txt');

 finally
  FText.Free;
 end;

end;

end;