How to read from a text file in Delphi?

Member

by emerald , in category: Other , 2 years ago

How to read from a text file in Delphi?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by evans , 2 years ago

@emerald  Watching what to read and looking from what file. Files are different: text, binary, database files, etc. If, for example, you have a test file, then use the TStringList class to read it;

Example:

1
2
3
4
5
6
7
8
9
var Liast: TStringList;
	 FileName: string;
begin
	FileName:= 'C:\Temp\Test.txt';
	List:= TStringList.Create;
	List.LoadFromFile(FileName);
	ShowMessage(List.Text); 
	List.Free;
end;

Member

by cyril , a year ago

@emerald 

In Delphi, you can read from a text file using the System.Text unit. Here's an example of how to read from a text file in Delphi:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var
  MyFile: TextFile;
  MyLine: string;
begin
  AssignFile(MyFile, 'C:MyFolderMyFile.txt'); // Assign the file path to MyFile
  Reset(MyFile); // Open the file for reading
  while not Eof(MyFile) do // Loop until end of file
  begin
    ReadLn(MyFile, MyLine); // Read one line from the file
    // Do something with MyLine
  end;
  CloseFile(MyFile); // Close the file
end;


In this example, the AssignFile procedure is used to assign the file path to the MyFile variable. The Reset procedure is used to open the file for reading. The while loop is used to read each line of the file until the end of the file is reached, and the ReadLn procedure is used to read each line of the file into the MyLine variable. Finally, the CloseFile procedure is used to close the file.


You can modify this example to suit your specific needs. For example, you can replace the // Do something with MyLine comment with your own code to process each line of the file.