textfiles delphi code example

Example 1: How to read text files in delphi

var
  Form1: TForm1;
 
implementation
{$R *.dfm} // Include form definitions
 
procedure TForm1.FormCreate(Sender: TObject);
var
  fileName : string;
  myFile   : TextFile;
  data     : string;

begin
  // Try to open a text file for writing to
  fileName := 'Test.txt';
  AssignFile(myFile, fileName);
  ReWrite(myFile);

  // Write to the file
  Write(myFile, 'Hello World');

  // Close the file
  CloseFile(myFile);

  // Reopen the file in read mode
  Reset(myFile);

  // Display the file contents
  while not Eof(myFile) do
  begin
    ReadLn(myFile, data);
    ShowMessage(data);
  end;

  // Close the file for the last time
  CloseFile(myFile);

  // Now see if the file exists
  if fileexists(fileName)
  then ShowMessage(fileName+' exists OK')
  else ShowMessage(fileName+' does not exist');

  // Delete the file and look again
  DeleteFile(fileName);
  if fileexists(fileName)
  then ShowMessage(fileName+' still exists!')
  else ShowMessage(fileName+' no longer exists');
end;
 
end.

Example 2: delphi read file

var
   myFile : TextFile;
   text   : string;
 
 begin
   // Try to open the Test.txt file for writing to
   AssignFile(myFile, 'Test.txt');
   ReWrite(myFile);
 
   // Write a couple of well known words to this file
   WriteLn(myFile, 'Hello');
   WriteLn(myFile, 'World');
 
   // Close the file
   CloseFile(myFile);
 
   // Reopen the file for reading
   Reset(myFile);
 
   // Display the file contents
   while not Eof(myFile) do
   begin
     ReadLn(myFile, text);
     ShowMessage(text);
   end;
 
   // Close the file for the last time
   CloseFile(myFile);
 end;