Pages

Tuesday, 29 January 2013

How to Open, Close, Read and Delete a File in Delphi XE2?

How to Open, Close, Read and Delete a File in Delphi XE2?

File Handling is very simple in delphi programming language. Here is a simple delphi program example for file handling. Following delphi program opens, writes and reads a file. After that the file is closed and finally deleted. Opening a file, reading / writing a file and deleting files are very common functionalities used in any delphi application. Following delphi program example for file handling does the same in very simple way.

procedure MyForm.HowToOpenCloseAndDeleteFile;
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 delete the file
  if DeleteFile(fileName) then ShowMessage(fileName+' deleted')
  else ShowMessage(fileName+' not deleted');
end;

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.