C++ Builder Tutorials

C++ Builder: File Operations


You may want to check first whether a file exists. If it does, then you may want to copy, move, or delete it.

TFile::Copy(FileName, NewFileName, Overwrite)

TFile::Move(FileName, NewFileName)


Parameters of the functions:

  • FileName: path plus name of an existing file.
  • NewFileName: path plus name of the new file.
  • Overwrite: if true, the file is overwritten.

Directory operations

TDirectory::Exists(Path, FollowLink) checks whether a given directory exists. It returns true if the given path exists and is a directory, and false otherwise.
Parameter FollowLink specifies if it is a "symbolic link file", a special type of file containing a reference to another file or directory; that's not the case here, so we pass the value false.

TDirectory::CreateDirectory(Path) creates a new directory (folder). If the directories given in Path do not yet exist, CreateDirectory attempts to create them.

TDirectory::Delete(Path, Recursive) deletes a directory. If the parameter Recursive is false, nonempty directories will not be deleted.

TDirectory::Copy(Source, Destination) copies a directory.

Important notes

  • The declarations of TFile and TDirectory are located in System.IOUtils. For the functions used in our examples, you have to add the following line to your project's main unit (usually Unit1.cpp), just above the line #include "Unit1.h":
    #include <System.IOUtils.hpp>
  • C++ treats a backslash as an "escape" character. Thus, "\" must be coded as "\\".


Copy a file:

void __fastcall TForm1::btnCopyClick(TObject *Sender)
  String Source = "D:\\Test\\File1.txt";
  String Dest = "D:\\Test\\File2.txt";
  if (FileExists(Source))
    TFile::Copy(Source, Dest, true);
    ShowMessage("The source file does not exist");

Move a file:

void __fastcall TForm1::btnMoveClick(TObject *Sender)
  String OldName = "D:\\Test\\File1.txt";
  String NewName = "D:\\Test\\File2.txt";
  if (!FileExists(OldName))
    ShowMessage("The file does not exist");
  else if (FileExists(NewName))
    ShowMessage("The destination file already exists");
    TFile::Move(OldName, NewName);

Delete a file:

void __fastcall TForm1::btnDeleteClick(TObject *Sender)
String TheFile = "D:\\Test\\File2.txt"; if (FileExists(TheFile)) TFile::Delete(TheFile); else ShowMessage("The file does not exist"); }

Create a directory:

void __fastcall TForm1::btnCreateDirClick(TObject *Sender)
  String Dir = "D:\\Test\\Test2";

Delete a directory:

void __fastcall TForm1::btnDeleteDirClick(TObject *Sender)
  String Dir = "D:\\Test\\Test2";
  if (TDirectory::Exists(Dir, false))
    TDirectory::Delete(Dir, true);
    ShowMessage("The directory does not exist");

Copy a directory:

void __fastcall TForm1::btnCopyDirClick(TObject *Sender)
  String Source = "D:\\Test";
  String Dest = "D:\\Test2";
  if (TDirectory::Exists(Source, false))
    TDirectory::Copy(Source, Dest);
    ShowMessage("The directory does not exist");