Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How operate on TFileStream

Tags:

delphi

pascal

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];
like image 971
Błażej Avatar asked Dec 12 '11 15:12

Błażej


2 Answers

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;
like image 189
RRUZ Avatar answered Sep 27 '22 23:09

RRUZ


I newer versions of Delphi you can use TStreamReader / TStreamWriter here is an example of using TStreamReader ... this is only for manipulating text files

var
  SR : TStreamReader;
  line : String;
begin
  SR := TStreamReader.Create('D:\test.txt');
  while not (SR.EndOfStream) do
  begin
    line := SR.ReadLine;
    ShowMessage(line);
  end;
  SR.Free;
 end;
like image 44
opc0de Avatar answered Sep 27 '22 23:09

opc0de