C++ Builder

La Isla Bonita



Delete All Files in a Given Directory
Delete All Files in a Given Directory


Description

In this article I develop a high level function to delete all files in a given directory. This function is called Delete_AllFiles() and is based on the Win32 API: SHFileOperation().

DeleteAllFiles.cpp

#include <vcl.h>
#pragma hdrstop

#include "DeleteAllFiles.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1*  Form1;
TButton* Button1;

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
    Width    = 400;
    Height   = 200;
    Color    = clNavy;
    Position = poScreenCenter;

    Button1 = new TButton(this);
    Button1->Parent = this;
    Button1->Top   = Height/2;
    Button1->Width = 150;
    Button1->Left  = (Width - Button1->Width)/2;
    Button1->Height  = 50;
    Button1->Caption = "Delete Files";
    Button1->OnClick = Button1Click;
}
//---------------------------------------------------------------------------

void Delete_AllFiles(TForm* pForm, char* s)
{
    char Buffer[MAX_PATH];

    // Create an object of the class SHFILEOPSTRUCT.
    //
    SHFILEOPSTRUCT oFile;

    memset(Buffer, 0, sizeof(Buffer));       //Init Buffer to 0
    memset(&oFile, 0, sizeof(oFile));        //Set Structure to 0

    // Make the application (Form1) to be the Owner of the
    // Progress Dialog Box that is displayed while
    // the delete operation takes place
    //
    oFile.hwnd = pForm->Handle;

    //Define the File Operation to be performed
    //
    oFile.wFunc = FO_DELETE;

    //Set the directory you want to delete
    //
    strcpy(Buffer, s);
    oFile.pFrom  = Buffer;
    oFile.fFlags = FOF_ALLOWUNDO;

    //Win 32 API
    //
    SHFileOperation(&oFile);
}
//----------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    Delete_AllFiles(Form1, "c:\\__TEST\\*.*");
}

DeleteAllFiles.h

#ifndef DeleteAllFilesH
#define DeleteAllFilesH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:	// IDE-managed Components
        void __fastcall Button1Click(TObject *Sender);
private:	// User declarations
public:		// User declarations
        __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif

Homepage

Copyright © 1997-2002 Rodolfo A. Frino. All rights reserved.