In this section, we will explore how to handle files in Delphi/Object Pascal. File handling is a crucial aspect of programming, allowing you to read from and write to files, which is essential for data storage and retrieval.

Key Concepts

  1. File Types: Understanding different file types in Delphi.
  2. File Operations: Basic operations such as opening, reading, writing, and closing files.
  3. Text Files: Handling text files specifically.
  4. Binary Files: Handling binary files.
  5. File Management: Managing file paths, checking file existence, and deleting files.

File Types

Delphi supports several file types, but the most common are:

  • Text Files: Used for reading and writing text.
  • Binary Files: Used for reading and writing binary data.

Basic File Operations

Opening a File

To open a file, you need to declare a file variable and associate it with a physical file.

var
  MyFile: TextFile;
begin
  AssignFile(MyFile, 'example.txt');
  Reset(MyFile); // Open the file for reading
  // or
  Rewrite(MyFile); // Open the file for writing
end;

Reading from a File

To read from a text file, you can use the ReadLn procedure.

var
  MyFile: TextFile;
  Line: string;
begin
  AssignFile(MyFile, 'example.txt');
  Reset(MyFile);
  while not Eof(MyFile) do
  begin
    ReadLn(MyFile, Line);
    WriteLn(Line); // Output the line to the console
  end;
  CloseFile(MyFile);
end;

Writing to a File

To write to a text file, you can use the WriteLn procedure.

var
  MyFile: TextFile;
begin
  AssignFile(MyFile, 'example.txt');
  Rewrite(MyFile);
  WriteLn(MyFile, 'Hello, World!');
  CloseFile(MyFile);
end;

Closing a File

Always close a file after you are done with it to free up system resources.

CloseFile(MyFile);

Handling Text Files

Text files are the most straightforward to handle. Here is a complete example of reading from and writing to a text file.

var
  MyFile: TextFile;
  Line: string;
begin
  // Writing to a file
  AssignFile(MyFile, 'example.txt');
  Rewrite(MyFile);
  WriteLn(MyFile, 'Hello, World!');
  WriteLn(MyFile, 'This is a text file.');
  CloseFile(MyFile);

  // Reading from a file
  AssignFile(MyFile, 'example.txt');
  Reset(MyFile);
  while not Eof(MyFile) do
  begin
    ReadLn(MyFile, Line);
    WriteLn(Line);
  end;
  CloseFile(MyFile);
end;

Handling Binary Files

Binary files are used for storing data in binary format. Here is an example of writing and reading integers to/from a binary file.

var
  MyFile: File of Integer;
  Number: Integer;
begin
  // Writing to a binary file
  AssignFile(MyFile, 'example.dat');
  Rewrite(MyFile);
  for Number := 1 to 10 do
    Write(MyFile, Number);
  CloseFile(MyFile);

  // Reading from a binary file
  AssignFile(MyFile, 'example.dat');
  Reset(MyFile);
  while not Eof(MyFile) do
  begin
    Read(MyFile, Number);
    WriteLn(Number);
  end;
  CloseFile(MyFile);
end;

File Management

Checking File Existence

You can check if a file exists using the FileExists function.

if FileExists('example.txt') then
  WriteLn('File exists')
else
  WriteLn('File does not exist');

Deleting a File

To delete a file, use the DeleteFile function.

if DeleteFile('example.txt') then
  WriteLn('File deleted successfully')
else
  WriteLn('Failed to delete file');

Practical Exercises

Exercise 1: Write and Read Text File

Task: Write a program that writes a list of names to a text file and then reads and displays them.

Solution:

var
  MyFile: TextFile;
  Names: array[1..3] of string = ('Alice', 'Bob', 'Charlie');
  Line: string;
  i: Integer;
begin
  // Writing to a file
  AssignFile(MyFile, 'names.txt');
  Rewrite(MyFile);
  for i := 1 to 3 do
    WriteLn(MyFile, Names[i]);
  CloseFile(MyFile);

  // Reading from a file
  AssignFile(MyFile, 'names.txt');
  Reset(MyFile);
  while not Eof(MyFile) do
  begin
    ReadLn(MyFile, Line);
    WriteLn(Line);
  end;
  CloseFile(MyFile);
end;

Exercise 2: Write and Read Binary File

Task: Write a program that writes an array of integers to a binary file and then reads and displays them.

Solution:

var
  MyFile: File of Integer;
  Numbers: array[1..5] of Integer = (10, 20, 30, 40, 50);
  Number: Integer;
  i: Integer;
begin
  // Writing to a binary file
  AssignFile(MyFile, 'numbers.dat');
  Rewrite(MyFile);
  for i := 1 to 5 do
    Write(MyFile, Numbers[i]);
  CloseFile(MyFile);

  // Reading from a binary file
  AssignFile(MyFile, 'numbers.dat');
  Reset(MyFile);
  while not Eof(MyFile) do
  begin
    Read(MyFile, Number);
    WriteLn(Number);
  end;
  CloseFile(MyFile);
end;

Common Mistakes and Tips

  • Forgetting to Close Files: Always ensure you close files after operations to avoid memory leaks and file corruption.
  • File Path Issues: Use absolute paths or ensure the working directory is correct when dealing with file paths.
  • Error Handling: Implement error handling to manage file access issues, such as missing files or permission errors.

Conclusion

In this section, we covered the basics of file handling in Delphi/Object Pascal, including how to open, read, write, and close both text and binary files. We also discussed file management techniques such as checking for file existence and deleting files. By practicing the provided exercises, you should now have a solid understanding of file handling in Delphi.

Delphi/Object Pascal Programming Course

Module 1: Introduction to Delphi/Object Pascal

Module 2: Control Structures and Procedures

Module 3: Working with Data

Module 4: Object-Oriented Programming

Module 5: Advanced Delphi Features

Module 6: GUI Development with VCL and FMX

Module 7: Web and Mobile Development

Module 8: Best Practices and Design Patterns

Module 9: Final Project

© Copyright 2024. All rights reserved