デルファイはtxtファイルの内容をどのように読み取るのか?

Delphiでtxtファイルの内容を読み取るには、TStringListコンポーネントとTFileStreamコンポーネントを使用することができます。以下は簡単なサンプルコードです:

procedure ReadTxtFile(const FileName: string; var Content: TStringList);
var
  FileStream: TFileStream;
begin
  Content.Clear;
  FileStream := TFileStream.Create(FileName, fmOpenRead);
  try
    Content.LoadFromStream(FileStream);
  finally
    FileStream.Free;
  end;
end;

上記のコードでは、まずTFileStreamオブジェクトを作成してtxtファイルを開き、その後、ファイルの内容をTStringListにロードします。以下は使用例です。

procedure TForm1.Button1Click(Sender: TObject);
var
  Content: TStringList;
begin
  Content := TStringList.Create;
  try
    ReadTxtFile('example.txt', Content);
    Memo1.Lines.Assign(Content);
  finally
    Content.Free;
  end;
end;

上記の例では、txtファイルの内容を保存するTStringListオブジェクトを作成し、その内容をMemo1コントロールに表示しました。必要に応じて上記のコードを変更および拡張することができます。

bannerAds