How to Implement File Input/Output In Delphi?

10 minutes read

In Delphi, implementing file input/output (I/O) involves opening files, reading data from them, writing data to them, and closing the files. Here's a step-by-step guide:

  1. Declare a variable of the TextFile type to represent the file to be accessed. For example, var MyFile: TextFile;. This variable will act as a file handle.
  2. Use the AssignFile procedure to associate the file handle (MyFile) with the desired file. For example, AssignFile(MyFile, 'C:\path\to\file.txt');.
  3. Open the file using the Reset procedure. For example, Reset(MyFile);. This will open the file for reading.
  4. Read data from the file using the ReadLn procedure. For example, ReadLn(MyFile, MyString); will read a line of text from the file and store it in the string variable MyString. You can use loops to read multiple lines of data.
  5. Write data to the file using the Write or WriteLn procedures. For example, WriteLn(MyFile, 'Hello, World!'); will write the specified string to the file, followed by a newline character.
  6. Close the file using the CloseFile procedure. For example, CloseFile(MyFile);. It is important to close the file after you have finished reading from or writing to it to free system resources.
  7. Repeat the above steps as needed to perform further file I/O operations.


Remember to handle any exceptions that may occur during file I/O operations using try-except blocks to gracefully handle errors and prevent your application from crashing.


File I/O in Delphi can be used to read and write various types of data, such as integers, floating-point numbers, and records, besides the simple text shown in the example. Additionally, there are other file access modes and functions available for specific requirements, like appending to an existing file or checking if a file exists before opening it.

Best Delphi Books to Read in 2024

1
Delphi GUI Programming with FireMonkey: Unleash the full potential of the FMX framework to build exciting cross-platform apps with Embarcadero Delphi

Rating is 5 out of 5

Delphi GUI Programming with FireMonkey: Unleash the full potential of the FMX framework to build exciting cross-platform apps with Embarcadero Delphi

2
Delphi Cookbook: Recipes to master Delphi for IoT integrations, cross-platform, mobile and server-side development, 3rd Edition

Rating is 4.9 out of 5

Delphi Cookbook: Recipes to master Delphi for IoT integrations, cross-platform, mobile and server-side development, 3rd Edition

3
Mastering Pascal and Delphi Programming (Palgrave Master Series (Computing), 1)

Rating is 4.8 out of 5

Mastering Pascal and Delphi Programming (Palgrave Master Series (Computing), 1)

4
Delphi Cookbook - Second Edition

Rating is 4.7 out of 5

Delphi Cookbook - Second Edition

5
Delphi Programming Unleashed/Book and Disk

Rating is 4.6 out of 5

Delphi Programming Unleashed/Book and Disk

6
Mastering Delphi Programming: A Complete Reference Guide: Learn all about building fast, scalable, and high performing applications with Delphi

Rating is 4.5 out of 5

Mastering Delphi Programming: A Complete Reference Guide: Learn all about building fast, scalable, and high performing applications with Delphi

7
Programming and Problem Solving with Delphi

Rating is 4.4 out of 5

Programming and Problem Solving with Delphi

8
Delphi Programming for Dummies

Rating is 4.3 out of 5

Delphi Programming for Dummies

9
The Little Book Of Delphi Programming: Learn To Program with Object Pascal (Little Programming Books)

Rating is 4.2 out of 5

The Little Book Of Delphi Programming: Learn To Program with Object Pascal (Little Programming Books)


How to handle file exceptions in Delphi?

In Delphi, you can handle file exceptions, such as file not found or file access error, by using try..except blocks. Here's an example of how to do it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var
  FileHandle: THandle;
begin
  try
    // Attempt to open the file
    FileHandle := FileOpen('C:\path\to\file.txt', fmOpenRead);

    if FileHandle = INVALID_HANDLE_VALUE then
    begin
      // Raise an exception indicating the file could not be found
      raise Exception.Create('File not found');
    end;

    // Perform desired operations on the file

  except
    on E: Exception do
    begin
      // Handle the exception
      ShowMessage('Error: ' + E.Message);
    end;
  end;
end;


In this example, we use the FileOpen function to open the file in read-only mode. If the file is not found or an error occurs while opening it, an exception will be raised. We catch the exception in the except block and display an error message using the ShowMessage function.


You can also use different exception types like EFOpenError or EInOutError to handle specific file-related exceptions. Additionally, you can add multiple except blocks to handle different types of exceptions separately.


Remember to always release any resources, such as file handles, in a finally block to ensure proper cleanup, even in case of exceptions.


How to check if a file exists in Delphi?

To check if a file exists in Delphi, you can use the FileExists function from the SysUtils unit.


Here is an example code snippet:

1
2
3
4
5
6
7
uses
  SysUtils;

function FileExists(const FileName: string): Boolean;
begin
  Result := FileExists(FileName);
end;


You can use this function like this:

1
2
3
4
if FileExists('C:\path\to\file.txt') then
  ShowMessage('File exists')
else
  ShowMessage('File does not exist');


Replace 'C:\path\to\file.txt' with the path and name of the file you want to check. The FileExists function returns True if the file exists and False if it does not.


How to read and write data from a CSV file in Delphi?

To read and write data from a CSV file in Delphi, you can use the TStreamReader and TStreamWriter classes from the System.IOUtils unit. Here is an example:


Reading data from a CSV file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
var
  inputFile: TStreamReader;
  line: string;
  values: TArray<string>;
begin
  inputFile := TStreamReader.Create('file.csv');
  try
    while not inputFile.EndOfStream do
    begin
      line := inputFile.ReadLine;
      values := line.Split(','); // Splitting the line into an array of values

      // Access the values and process them as needed
      ShowMessage(values[0]); // Displaying the first value, for example
    end;
  finally
    inputFile.Free;
  end;
end;


In this example, we create a TStreamReader object to read the file.csv file. We then use a while loop to read each line of the file by calling the ReadLine method of the TStreamReader object. We split each line into an array of values using the Split method and process the values as needed.


Writing data to a CSV file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var
  outputFile: TStreamWriter;
  line: string;
begin
  outputFile := TStreamWriter.Create('file.csv');
  try
    line := 'value1,value2,value3'; // Example line format
    outputFile.WriteLine(line);

    // Write additional lines as needed
  finally
    outputFile.Free;
  end;
end;


In this example, we create a TStreamWriter object to write to the file.csv file. We use the WriteLine method to write a line of data to the file. You can write additional lines as needed.


Remember to include the System.IOUtils unit in your uses clause to use the TStreamReader and TStreamWriter classes.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

If you encounter the Delphi &#34;out of memory&#34; error, there are a few steps you can take to try and resolve it:Check system resources: Ensure that your computer has sufficient memory available for the Delphi application to run. Close any unnecessary progr...
To run a Delphi 7 project without debugging, follow these steps:Open your Delphi 7 project by clicking on the project file (.dpr) in the Project Manager or by selecting &#34;Open&#34; from the File menu. Once your project is opened, go to the Run menu at the t...
String manipulation in Delphi is a common task that involves performing various operations on strings, such as concatenation, extraction, searching, and replacing. Delphi provides a wide range of functions and techniques to manipulate strings efficiently. Here...