Description
This example shows how to copy a directory with all its subdirectories
to another (existing) directory.
This functionality is achieved with the following function
void Copy_Subdirectory(String Path, String PathDest);
which takes two parameters:
1) Path: Source Path (eg "C:\\SourceDir\\")
2) PathDest: Destination Path (eg "C:\\DestDir\\")
and returns void.
Form1 contains a TButton.
Files
CopySubdirectory.cpp
#include <vcl.h>
#pragma hdrstop
#include <Filectrl.hpp>
#include "CopySubdirectory.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void Copy_Subdirectory(String Path, String PathDest)
{
if ( Path[Path.Length()] != '\\' )
Path += String("\\");
String mask = ( Path + "*.*" );
WIN32_FIND_DATA fd = {0};
HANDLE h = FindFirstFile( mask.c_str(), &fd ); //Win32 API
if( h != INVALID_HANDLE_VALUE )
{
while( FindNextFile( h, &fd ) ) //Win32 API
{
String File = fd.cFileName;
if( File == "." || File == ".." )
continue;
if( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
//FILE ATTRIBUTE IS A DIRECTORY:
if (!CreateDir(PathDest + File)) //VCL function
ShowMessage("Cannot create directory :" + PathDest + File);
String SourceDir = Path + File + "\\";
String DestDir = PathDest + File + "\\";
//Recursive call
Copy_Subdirectory(SourceDir, DestDir);
}
else
{
//FILE ATTRIBUTTE IS NOT A DIRECTORY (IS A FILE):
if ( !CopyFile( (Path + File).c_str(),
(PathDest + File).c_str(), FALSE )) //Win32 API
{
GetLastError();
ShowMessage("Cannot copy file - errno = " + String(errno));
}
}
}
FindClose( h ); //Win 32 API
}
else
{
ShowMessage("Error: FindFirstFile() returned an Invalid Handle");
}
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
//Usage
//
Copy_Subdirectory("c:\\SourceDir\\", "c:\\DestDir\\");
}
//---------------------------------------------------------------------------
CopySubdirectory.h
#ifndef CopySubdirectoryH
#define CopySubdirectoryH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TButton *Button1;
void __fastcall Button1Click(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
//-------------------------------------------------------------
Copyright © 1997-2003 Rodolfo A. Frino. All rights reserved.