Programming C++Builder Manipulating Files--Delete, Find, Rename and Copy Files in C++Builder

Several common file operations are built into the BaseCLX runtime library. The procedures and functions 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.

Caution: Although the Object Pascal language is not case sensitive, the Linux operating system is. Be attentive to case when working with files in cross-platform applications.

The following topics describe how to use runtime library routines to perform file manipulation tasks:

Delete 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 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, for example:

DeleteFile("c:\\my documents\\test.txt");

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. The declaration for TSearchRec is:

struct TSearchRec
{ int Time; // time stamp of the file int Size; // size of the file in bytes int Attr; // file attribute flags AnsiString Name; // filename and extension int ExcludeAttr; // file attribute flags for files to ignore unsigned FindHandle; _WIN32_FIND_DATAA FindData; // structure with addition information } ;

If a file is found, the fields of the TSearchRec type parameter are modified to describe the found file. You can test Attr against the following attribute constants or values to determine if a file has a specific attribute:

Constant Value Description
faReadOnly 0x00000001 Read-only files
faHidden 0x00000002 Hidden files
faSysFile 0x00000004 System files
faVolumeID 0x00000008 Volume ID files
faDirectory 0x00000010 Directory files
faArchive 0x00000020 Archive files
faAnyFile 0x0000003F Any file

To test for an attribute, combine the value of the Attr field with the attribute constant using the & 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 & faHidden > 0). Attributes can be combined by OR抜ng their constants or values. For example, to search for read-only and hidden files in addition to normal files, pass (faReadOnly | faHidden) as the Attr parameter.

Example: This example uses a label, a button named Search, and a button named Again on a form. When the user clicks the Search button, the first file in the specified path is found, and the name and the number of bytes in the file appear in the label's caption. Each time the user clicks the Again button, the next matching filename and size is displayed in the label:

TSearchRec SearchRec; // global variable
void __fastcallTForm1::SearchClick(TObject *Sender)
FindFirst("c:\\Program Files\\bcb6\\bin\\*.*", faAnyFile, SearchRec);
Label1->Caption = SearchRec->Name + " is " + IntToStr(SearchRec.Size) + " bytes in size";

void __fastcallTForm1::AgainClick(TObject *Sender)
if (FindNext(SearchRec) == 0)
Label1->Caption = SearchRec->Name + " is " + IntToStr(SearchRec.Size) + " bytes in size";

Note: In cross-platform applications, you should replace any hard-coded pathnames with the correct pathname for the system or use environment variables (on the Environment Variables page when you choose Tools|Environment Options) to represent them.

Rename a File.

To change a file name, use the RenameFile function:

extern PACKAGE bool __fastcall RenameFile(const AnsiString OldName, const AnsiString NewName);

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 (!RenameFile("OLDNAME.TXT","NEWNAME.TXT"))

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.

Note: RenameFile in the BaseCLX runtime library is a wrapper around the Windows API MoveFile function, so MoveFile will not work across drives either.

Copy a File.

The BaseCLX 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.

File Date-Time Routines.

The FileAge, FileGetDate, and FileSetDate routines operate on operating system date-time 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 an integer parameter which takes a file handle. 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. See Using file streams for more information.

Add comment

Security code

Programming - C++Builder