delphi textfile 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: create text file delphi
procedure MakeAStringlistAndSaveThat;
var
MyText: TStringlist;
begin
MyText:= TStringlist.create;
try
MyText.Add('line 1');
MyText.Add('line 2');
MyText.SaveToFile('c:\folder\filename.txt');
finally
MyText.Free
end; {try}
end;