Manipulating Files in Delphi

Several common file operations are built into the runtime library. The routines for working with files operate at a high level. For most routines, you specify the name of the file and the routine makes the necessary calls to the operating system for you.

In some cases, you use file handles instead. Although the Delphi language is not case sensitive, the Linux operating system is. Be attentive to case when working with files in cross-platform applications.

Deleting a file

Deleting a file erases the file from the disk and removes the entry from the disk's directory. There is no corresponding operation to restore a deleted file, so applications should generally allow users to confirm before deleting files. To delete a file, pass the name of the file to the DeleteFile function:

DeleteFile(FileName);

DeleteFile returns True if it deleted the file and False if it did not (for example, if the file did not exist or if it was read-only). DeleteFile erases the file named by FileName from the disk.

Finding a file

There are three routines used for finding a file: FindFirst, FindNext, and FindClose. FindFirst searches for the first instance of a filename with a given set of attributes in a specified directory. FindNext returns the next entry matching the name and attributes specified in a previous call to FindFirst.

FindClose releases memory allocated by FindFirst. You should always use FindClose to terminate a FindFirst/FindNext sequence. If you want to know if a file exists, a FileExists function returns True if the file exists, False otherwise.

The three file find routines take a TSearchRec as one of the parameters. TSearchRec defines the file information searched for by FindFirst or FindNext. If a file is found, the fields of the TSearchRec type parameter are modified to describe the found file.

type TFileName = string; TSearchRec = record Time: Integer;//Time contains the time stamp of the file. Size: Integer;//Size contains the size of the file in bytes. Attr: Integer;//Attr represents the file attributes of the file. Name: TFileName;//Name contains the filename and extension. ExcludeAttr: Integer; FindHandle: THandle; FindData: TWin32FindData;//FindData contains additional information such as //file creation time, last access time, long and short filenames. end;

On field of TSearchRec that is of particular interest is the Attr field. You can test Attr against the following attribute constants or values to determine if a file has a specific attribute:

faReadOnly - $00000001 faHidden - $00000002 faSysFile - $00000004 faVolumeID - $00000008 faDirectory - $00000010 faArchive - $00000020 faAnyFile - $0000003F

To test for an attribute, combine the value of the Attr field with the attribute constant using the and operator. If the file has that attribute, the result will be greater than 0. For example, if the found file is a hidden file, the following expression will evaluate to True:

(SearchRec.Attr and faHidden > 0).

Attributes can be combined by OR’ing their constants or values. For example, to search for read-only and hidden files in addition to normal files, pass the following as the Attr parameter.

(faReadOnly or faHidden).

Renaming a file

To change a file name, use the RenameFile function:

function RenameFile(const OldFileName, NewFileName: string): Boolean;

RenameFile changes a file name, identified by OldFileName, to the name specified by NewFileName. If the operation succeeds, RenameFile returns True. If it cannot rename the file (for example, if a file called NewFileName already exists), RenameFile returns False. For example:

if not RenameFile('OLDNAME.TXT','NEWNAME.TXT') then ErrorMsg('Error renaming file!');

You cannot rename (move) a file across drives using RenameFile. You would need to first copy the file and then delete the old one.

File date-time routines

The FileAge, FileGetDate, and FileSetDate routines operate on operating system datetime values. FileAge returns the date-and-time stamp of a file, or -1 if the file does not exist. FileSetDate sets the date-and-time stamp for a specified file, and returns zero on success or an error code on failure.

FileGetDate returns a date-and-time stamp for the specified file or –1 if the handle is invalid. As with most of the file manipulating routines, FileAge uses a string filename. FileGetDate and FileSetDate, however, use a Handle type as a parameter. To get the file handle either:

  • Use the FileOpen or FileCreate function to create a new file or open an existing file. Both FileOpen and FileCreate return the file handle.
  • Instantiate TFileStream to create or open a file. Then use its Handle property.

Copying a file

FindingAFile;RenamingAFile;FileDateTimeRoutines;DeletingAFileThe runtime library does not provide any routines for copying a file. However, if you are writing Windows-only applications, you can directly call the Windows API CopyFile function to copy a file.

Like most of the runtime library file routines, CopyFile takes a filename as a parameter, not a file handle. When copying a file, be aware that the file attributes for the existing file are copied to the new file, but the security attributes are not.

CopyFile is also useful when moving files across drives because neither the RenameFile function nor the Windows API MoveFile function can rename or move files across drives. For more information, see the Microsoft Windows online Help.