Interacting with the file system (reading configuration data, saving user documents, logging errors) is essential for almost all applications. Pascal offers both traditional, procedural methods and modern, object-oriented Stream classes.
1. Traditional File Handling (Procedural)
Traditional file I/O uses procedural functions to read and write entire lines or specific records. This method is often simpler for text files but less flexible for binary or networked data.
A. File Types
| Type | Purpose | Syntax Example |
TextFile | Standard text-only files (ASCII/Unicode). Read line-by-line. | var MyFile: TextFile; |
File of T | Typed Files. Binary files structured as an array of fixed-size records (T). | var DataFile: File of TCustomerRecord; |
File | Untyped Files. Low-level access for block reading/writing (e.g., system utilities). | var RawFile: File; |
B. Core Procedures
The following sequence is required for all traditional file operations:
| Procedure | Purpose |
AssignFile(F, FileName) | Links the internal file variable F to a specific external file on the disk. |
Reset(F) | Opens an existing file F for reading. Sets the file pointer to the beginning. |
Rewrite(F) | Creates a new file F for writing. If the file exists, its content is erased. |
Append(F) | Opens an existing text file F for writing and sets the file pointer to the end. (Text files only) |
CloseFile(F) | Releases the operating system lock on the file. Must be called after all operations. |
Eof(F) | End of File. Returns True when the file pointer is past the last record/character. |
C. Reading a Text File
program TextFileDemo;
var
F: TextFile;
Line: String;
begin
AssignFile(F, 'log.txt');
// Use try...except to handle file not found errors
try
Reset(F); // Open for reading
while not Eof(F) do // Loop until the end of the file
begin
Readln(F, Line); // Read one line from file F into variable Line
Writeln('Read: ', Line);
end;
except
on E: Exception do // Catch specific file I/O exceptions
Writeln('File Error: ', E.Message);
end;
CloseFile(F); // Essential cleanup
end.
2. Modern I/O: Streams (Object-Oriented)
The Stream model treats the data source (file, memory, network connection) as a continuous sequence of bytes. This object-oriented approach is more powerful, flexible, and essential for modern GUI frameworks (like VCL/Lazarus LCL) and complex data.
- Base Class: All streams inherit from the abstract class
TStream. - Key Feature: Streams use a Position property to track where the next read/write operation will occur.
A. Common Stream Classes
| Class | Purpose | Key Feature |
TFileStream | Reads/writes data to and from a disk file. | The most common stream for disk I/O. |
TMemoryStream | Reads/writes data entirely within the computer’s RAM. | Ideal for fast temporary data or network buffering. |
TStringStream | Reads/writes data using a String variable as the source/destination. | Simplifies string-based data exchange. |
B. Key Stream Methods
| Method | Purpose |
Create(FileName, Mode) | Constructor, opens/creates the file based on the Mode. |
Read(Buffer, Count) | Reads Count bytes into the specified Buffer variable. |
Write(Buffer, Count) | Writes Count bytes from the Buffer variable to the stream. |
Seek(Offset, Origin) | Moves the stream’s internal Position pointer. Origin can be soFromBeginning, soFromCurrent, or soFromEnd. |
C. Example: Using TFileStream
uses
SysUtils, Classes; // Classes unit provides TFileStream, TStream
procedure SaveBinaryData(FileName: String; Data: String);
var
Stream: TFileStream;
BytesWritten: Integer;
begin
Stream := TFileStream.Create(FileName, fmCreate); // fmCreate = create new file
try
// Write the raw bytes of the string to the file
BytesWritten := Stream.Write(Data[1], Length(Data));
Writeln('Wrote ', BytesWritten, ' bytes.');
finally
// Always use try...finally to free the stream object (P2.4 rule)
Stream.Free;
end;
end;
3. File Utility Functions (SysUtils)
For common, simple file operations, the SysUtils unit (available in FPC/Lazarus/Delphi) provides convenient functions that abstract away the complexity.
| Function | Purpose | Example |
FileExists(FileName) | Checks if a file is present on the disk. | if FileExists('config.ini') then... |
DeleteFile(FileName) | Deletes the specified file. | DeleteFile('temp.tmp'); |
RenameFile(Old, New) | Renames a file. | RenameFile('old.dat', 'new.dat'); |
ExtractFileName(Path) | Returns only the filename portion of a full path. | ExtractFileName('C:\data\file.txt') $\rightarrow$ 'file.txt' |
