File I/O - Delphi Examples

There are 3 basic methods to perform File I/O The delphi help files suggest that you use the Pascal routines if you can.

File Manager Commands

SysUtils/FileOpen and System/AssignFile have different commands for many of these

See SysUtils / File-management routines and System / I/O routines

Change Directory SetCurrentDir('c:\path')
Make Directory CreateDir('c:\path')
Remove Directory RemoveDir('c:\path')
Change Drive (no known function)
Rename a File RenameFile('test.txt', 'string.tst')
ChangeFileExt('test.txt', 'doc')
Delete a File DeleteFile('c:\*.tst') - Don't know if wildcards are allowed
Search for File t_str := FileSearch('readme.txt', 'c:\;c:\windows');
t_int := FindFirst ('c:\*.tst', attr, F) ;
Current Drirectory t_str := GetCurrentDir ;
Get File Attributes temp = FileGetAttr('c:\filename.tst')
Get File Mode TSearchRec.Attr (use with FindFirst or FindNext)
Set File Attributes FileSetAttr('c:\filename.tst', faReadOnly)
Get File Length TSearchRec.Size (use with FindFirst or FindNext)
FileSize(var F)
Get File Date/Time tempDate := FileGetDate(Handle) ;
Set File Date/Time FileSetDate(Handle, Age)
Test File existance if FileExists('c:\filename.tst') then
Test Directory existance if DirectoryExists('c:\temp') then

AdjustLinesBreaks(const S: string): string; - adjusts all line breaks in the string S to be true CR/LF

File I/O Commands

Open File for I/O FileOpen(const FileName: string; Mode: Integer): Integer;
AssignFile(F, OpenDialog1.FileName);
Rewrite(var F: File [; Recsize: Word ] );
Append(var F: Text);
Get File Mode F.Mode or (F as TFileRec).Mode
Write to File FileWrite(Handle: Integer; const Buffer; Count: Integer): Integer;
Write to TextFile Writeln, Write
Write to File BlockWrite()
Read From TextFile Read, Readln
Read From File BlockRead()
Set Current LocationSeek(var F; N: Longint);
Get Current LocationFilePos(var F)
Length of File FileSize(var F)
End of File while not Eof(F1) do
Close File FileClose(Handle: Integer)
Closes All Files Not available in Delphi

  f1 : file;
  f2 : text;
  f3 : textfile;  // from AssignFile hlp

(* File type declarations from Delphi file help *)
  Person = record
    FirstName: string[15];
    LastName : string[25];
    Address  : string[35];
  PersonFile = file of Person;
  NumberFile = file of Integer;
  SwapFile = file;

TFileRec = 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;

File Search Commands

Files and directories may not have the same names. The more complicated FindFirst command must be used because FileExists does not find directories.

Testing for the Existance of a File

The following is from the reset example.
function FileExists(FileName: string): Boolean;
{ Boolean function that returns True if the file exists; otherwise,
  it returns False. Closes the file if it exists. }
  F: file;
  AssignFile(F, FileName);
  FileMode := 0;  ( Set file access to read only }
  FileExists := (IOResult = 0) and (FileName <> '');
end;  { FileExists }
In Delphi 5, FileExists is built-in.

Testing for the Existance of a Directory

FileExists(tt) does not find directories. Can use stream objects which have handles

With Delphi 5, you can use

Opening and Reading a File

The following is from the AssignFile example.
  F: TextFile;
  S: string;
  if OpenDialog1.Execute then     { Display Open dialog box }
    AssignFile(F, OpenDialog1.FileName);   { File selected in dialog box }
    Readln(F, S);                 { Read the first line out of the file }
    Edit1.Text := S;              { Put string in a TEdit control }
File copy - from the Eof, Read, Write example. To use this, create a form with a button, a Dialogs / OpenDialog component and a Dialogs / SaveDialog component. Double click the button (to open the source code) and paste the following code. Be sure that the code begins with var and not begin.
procedure TForm1.CopyFile();
  F1, F2: TextFile;
  Ch: Char;
  if OpenDialog1.Execute then begin
    AssignFile(F1, OpenDialog1.Filename);
    if SaveDialog1.Execute then begin
      AssignFile(F2, SaveDialog1.Filename);
      while not Eof(F1) do
        Read(F1, Ch);
        Write(F2, Ch);

end;  // of procedure TForm1.CopyFile()

Author: Robert Clemenzi -
URL: http:// / user / clemenzi / technical / Languages / Delphi / DelphiFileIO.htm