如何操作TFileStream

Bła*_*żej 6 delphi pascal

你好,我最近换TextFileTFileStream.我从不使用它,所以我的问题很小.

  • 在将其分配给变量后,如何在文件中添加一些内容?
  • 我怎样才能阅读该文件的某些表格?

我需要定义的行格式文件,所以我做的是这样的:

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);
Run Code Online (Sandbox Code Playgroud)

然后当我需要第二行时

edit1.text = linia_klienta[1];
Run Code Online (Sandbox Code Playgroud)

RRU*_*RUZ 13

如果您需要读取文本文件并访问每一行,请尝试使用此类的TStringList类,您可以加载文件,读取数据(使用索引访问每一行)并保存数据.

这样的事情

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;
Run Code Online (Sandbox Code Playgroud)

  • 使用TStrings是非常低效的内存. (3认同)

opc*_*0de 6

我可以在这里使用TStreamReader/TStreamWriter的新版Delphi 是一个使用TStreamReader的例子...这只是用于操作文本文件

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;
Run Code Online (Sandbox Code Playgroud)