Delphi Files, Directories, Disks, I/O
A. Files B. Directories C. Disks/Drives D. File I/O E. Stream I/O F. Port I/O

(bookmark.gif (183 bytes) Bookmark)

Topic Description Unit
general info File I/O, Delphi in a Nutshell, pp. 26-27  
{$I+}, {$I-} See IOResults and Critical Errors Page  
Absolute Sectors Read/Write absolution positions on disk

Absolute Read/Write HardDisk on Win32 Platform. Delphi 3 full source included.  http://delphi.icm.edu.pl/ftp/d30free/abs_rw.zip

 
bookmark.gif (183 bytes)Append procedure Append(var f:  Text);
Opens an existing file so that new text can be added

The procedure Append is intended for text files.  If you use Append on a file of another type the compiler does not catch the error and appends anyway.   D5 Bug.

Example:  (Append vs. Rewrite)

// Write Log file.
PROCEDURE WriteToLog(CONST key: STRING; CONST level: INTEGER; CONST description: STRING);
  VAR
    DirectoryName: STRING;
    FileName:  STRING;
    LogFile:  TextFile;
BEGIN
  DirectoryName := ExtractFilePath(ParamStr(0)) + 'LOG';

  // Create directory, if necessary.
  IF       NOT FileCtrl.DirectoryExists(DirectoryName)
  THEN FileCtrl.ForceDirectories(DirectoryName);

  FileName := FormatDateTime('yyyymm', Now) + '.LOG';
  AssignFile(LogFile, DirectoryName + '\' + FileName);

  TRY
    IF        SysUtils.FileExists(DirectoryName + '\' + FileName)
    THEN Append(LogFile)    // If existing file
    ELSE Rewrite(Logfile);     // Create if new

    IF       Level = 0
    THEN WRITELN(LogFile) // blank line
    ELSE WRITELN (LogFile, FormatDateTime('dd hh:nn:ss', Now), ' ', Format('%-16s', [key]), ' ', description);

    CloseFile(LogFile)
  EXCEPT
    // Ignore exceptions while writing log files
  END;

END {WriteToLog};
System
Assign Use AssignFile below.  Exists only for backward compatibility. System
AssignFile procedure AssignFile(var F);
Associates the name of an external file with a file variable.

See:
- efg's UseNet Reply about AssignFile and UNC names 
ExclusiveIO Example
- example as part of  Append  information (above)
- College Student Guide to Reading and Writing Files, Borland's TI 641D
- How to copy files in Delphi, Borland's TI 910D

System
AssignPrn procedure AssignPrn(var F:  Text);
Assigns a text-file variable to the printer.
Printers
bookmark.gif (183 bytes)BlockRead D1:
procedure BlockRead(var F:  File; var Buf; Count:  Word; [; var Result:   Word]);

D2-D4:
procedure BlockRead(var F:  File; var Buf; Count: Integer; [; var AmtTransferred:   Integer]);

See:
- Erwin's Ahlers' UseNet Post explaining Count parameter
- Read and BlockRead file function failure in 32 bit, FAQ 2798D
- How to copy files in Delphi, Borland's TI 910D
- Fragment of  Patching EXE with CRC-32 between Sentinels
ExclusiveIO Example.

- Bob Villiers' UseNet Post with VarArrayLoadFile, which loads a bitmap into a variant using BlockRead
- Example from CRC Lab Report:

PROCEDURE CalcFileCRC32 (FromName: STRING; VAR CRCvalue: INTEGER;
  VAR IOBuffer: pointer; BufferSize: INTEGER; VAR TotalBytes: INTEGER;
  VAR error: INTEGER);
  VAR
  BytesRead: INTEGER;
  FromFile : FILE;
BEGIN
  FileMode := 0; {Turbo default is 2 for R/W; 0 is for R/O}
  CRCValue := $FFFFFFFF;
  ASSIGN (FromFile,FromName);
  {$I-} RESET (FromFile,1); {$I+}
  error := IOResult;
  IF       error = 0
  THEN BEGIN
    TotalBytes := 0;

    REPEAT
      BlockRead (FromFile,IOBuffer^,BufferSize,BytesRead);
      CalcCRC32 (IOBuffer,BytesRead,CRCvalue);
      INC (TotalBytes, BytesRead)
    UNTIL BytesRead = 0;
    CLOSE (FromFile)
  END;
  CRCvalue := NOT CRCvalue
END {CalcFileCRC32};
System
BlockWrite D1:
procedure BlockWrite(var F:  File; var Buf; Count:  Word; [; var Result:   Word]);

D2-D4:
procedure BlockWrite(var F:  File; var Buf; Count: Integer; [; var AmtTransferred:   Integer]);

See: 
- fragment of  Patching EXE with CRC-32 between Sentinels
- How to copy files in Delphi, Borland's TI 910D

System
Close Use CloseFile below.  Exists only for backward compatibility. System
Close a File How do I close a file that was opened in a DLL (Delphi made) and called from VB?  
Borland's TI 561D
CloseFile procedure CloseFile(var F);
Associates the name of an external file with a file variable.

Can be abbreviated as Close for backward compatibility.

See
ExclusiveIO Example
- College Student Guide to Reading and Writing Files, Borland's TI 641D

System
DeleteFile function DeleteFile(const FileName:   string):  Boolean;
Erase the specified file.
SysUtils
EOF function Eof(var F):  Boolean;

Text files:
function Eof [ (Var F: Text) ]:  Boolean;

Tests whether the current file position is the end-of-file.

System
EOLN function Eoln [ (Var F: Text) ]:  Boolean;

Tests whether the current file position is the end-of-line of a text file.

System
Erase procedure Erase(var F);
Deletes the external file associate with F.
System
Exception Handling See IOResults and Critical Errors Page  
Exclusive I/O Delphi only directly supports exclusive "reads" from typed or untyped files.
This UNIT provides a TExclusiveIO class to read a TextFile in an exclusive mode.
Use in a network when files are shared.  Also, handles either DOS or UNIX format of
ASCII files.
ExclusiveIO
File I/O "Dealing with File I/O," Delphi 5 Developer's Guide (pp. 338-360) by Teixeria and Pacheco  
File Input and Output Delphi in a Nutshell,  pp. 494-497  
File mode constants Use the file mode constants when opening and closing disk files.  The Mode field of TFileRec and TTextRec will contain one of these values.
fmClosed $D7B0
fmInput $D7B1
fmOutput $D7B2
fmInOut $D7B3
SysUtils
File Open Mode constants Use the file open mode constants to control the shareability
of a file or stream when it's opened.
fmOpenRead $0000 Open for read access only
fmOpenWrite $0001 Open for write access only
fmOpenReadWrite $0002 Open for read and write access
fmShareCompat $0000 Compatible with the way FCBs are opened
fmShareExclusive $0010 Open the file, disallowing other applications to open it for reading or writing.
fmShareDenyWrite $0020 Open the file, disallowing other applications to open it for writing.

Philippe Ranger's UseNet Post with File Locking Example

fmShareDenyRead $0030 Open the file, disallowing other applications to open it for reading
fmShareDenyNone $0040 Open the file, disallowing other applications to open it for exclusive use.
SysUtils
FileClose procedure FileClose(Handle:  Integer);
Closes the specified file.

How to Match File Date/Time, Borland's TI 719D
AlterFileTimeStamp.TXT example.

SysUtils
FileCreate function FileCreate(const Filename:   string):  Integer;
Closes the specified file.
SysUtils
bookmark.gif (183 bytes)FileMode The FileMode variable (a byte) determines the access mode to use when typed and untyped files (not text files) are opened using the Reset procedure.  The default FileMode is 2.  Assigning another value to FileMode causes all subequent Resets to use that mode.

0 = Read Only, 1 = Write Only, 2= Read/Write

See:
ExclusiveIO Example using fmShareExclusive.
-  fragment of  Patching EXE.

System
FileOpen How to Match File Date/Time, Borland's TI 719D
AlterFileTimeStamp.TXT example.
SysUtils
FilePos   System
FileRead   SysUtils
FileSeek Read a text file backwards
www.preview.org/q/q1038.shtml
SysUtils
FileSetDate See AlterFileTimeStamp.TXT example.  
FileSize    
FileWrite   SysUtils
FlushFileBuffers Flush binary file from disk cache to disk, FAQ1926D  
IOResult See IOResults and Critical Errors Page System
input variable   System
LoadFromFile    
output variable   System
Read, ReadLn - College Student Guide to Reading and Writing Files, Borland's TI  641D
- How to readln longer than 255 chars (D1), Borland's TI 571D
- Read and BlockRead file function failure in 32 bit, Borland's FAQ 2798D
System
Reading & Writing Files College Student Guide to Reading and Writing Files, Borland's TI 641D  
Rename   System
Reset See:
- FileMode variable (above)
- fragment of  Patching EXE.
- How to copy files in Delphi, Borland's TI 910D
System
Rewrite See:
- fragment of  Patching EXE.
- College Student Guide to Reading and Writing Files, Borland's TI 641D
- How to copy files in Delphi, Borland's TI 910D
System
SaveToFile    
Seek Ken Aston's UseNet Post explaining "seek" on a text file (TextRead - a simple Seek access to text files in read mode.) System
SeekEof   System
SeekEoln   System
SetTextBuf
VAR
  FromBuffer: ARRAY[1..10240] OF CHAR; {speed up I/O}

...
SetTextBuf (FromFile, FromBuffer);
ASSIGN (FromFile, FromName);
System
Streams See Stream I/O page.  
System.FileMode See"File Open Modes" (above)  
Test Files The GenText program can be used to create up to 99,999,999 records in a file of up to about 5.9 GB.  Gen.ZIP  
TextFile System
TFileRec TFileRec is the internal format for typed and untyped files. TFileRec enables you to typecast a file variable to access its internal fields.  Note:    You would normally never declare a variable of this type.

type TFileRec =
packed record
  Handle: Integer;
  Mode: Integer;
  RecSize: Cardinal;
  Private: array[1..28] of Byte;
  UserData: array[1..32] of Byte;
  Name: array[0..259] of Char;
end;

SysUtils
TTextRec TTextRec is the internal format of a variable of type text. You would never declare a variable of this type. However, you can use TTextRec to typecast a text file variable to access the internal data fields, such as the file name.

TextBuf is the type of the Buffer entry in the TTextRec record, and indicates the size of the buffer used.

Note:    Do not use this unless you are familiar with writing Object Pascal text file device drivers.

type
  PTextBuf = ^TTextBuf;
  TTextBuf = array[0..127] of Char;

  TTextRec =
  packed record
    Handle: Integer;
    Mode: Integer;
    BufSize: Cardinal;
    BufPos: Cardinal;
    BufEnd: Cardinal;
    BufPtr: PChar;
    OpenFunc: Pointer;
    InOutFunc: Pointer;
    FlushFunc: Pointer;
    CloseFunc: Pointer;
    UserData: array[1..32] of Byte;
    Name: array[0..259] of Char;
    Buffer: TTextBuf;
  end;

SysUtils
Truncate Call Truncate to cause the current file position to become end-of-file (Eof(F) is True).  F is a file variable of any type except a text file. Truncate does not work on text files. F must be open. System
Write/WriteLn See
- example under Append in File I/O
- College Student Guide to Reading and Writing Files, Borland's TI 641D
System

Links Verified 5 Mar 2000
Updated 27 Aug 2005


since 19 Apr 1999