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')
ForceDirectories('c:\path1\path2')
Remove Directory RemoveDir('c:\path')
RmDir(str)
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)
CloseFile(F1);
Closes All Files Not available in Delphi

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

(* File type declarations from Delphi file help *)
type
  Person = record
    FirstName: string[15];
    LastName : string[25];
    Address  : string[35];
  end;
  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;
end;


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. }
 var
  F: file;
begin
  {$I-}
  AssignFile(F, FileName);
  FileMode := 0;  ( Set file access to read only }
  Reset(F);
  CloseFile(F);
  {$I+}
  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.
var 
  F: TextFile;
  S: string;
begin
  if OpenDialog1.Execute then     { Display Open dialog box }
  begin
    AssignFile(F, OpenDialog1.FileName);   { File selected in dialog box }
    Reset(F);
    Readln(F, S);                 { Read the first line out of the file }
    Edit1.Text := S;              { Put string in a TEdit control }
    CloseFile(F);
  end;
end;
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();
var
  F1, F2: TextFile;
  Ch: Char;
begin
  if OpenDialog1.Execute then begin
    AssignFile(F1, OpenDialog1.Filename);
    Reset(F1);
    if SaveDialog1.Execute then begin
      AssignFile(F2, SaveDialog1.Filename);
      Rewrite(F2);
      while not Eof(F1) do
      begin
        Read(F1, Ch);
        Write(F2, Ch);
      end;
      CloseFile(F2);
    end;
    CloseFile(F1);

  end;
end;  // of procedure TForm1.CopyFile()


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