Write the Deltree program with Delphi

zhaozj2021-02-08  224

Delphi provides many functions regarding file operations, where there is a directory creation and deletion of a directory operation, set the current directory, get the current directory, etc. The deletion of the directory has a function (Procedure) RMDIR, but they can only delete the empty directory, and they cannot be deleted for non-empty directories. To implement the deletion of the entire directory tree (Deltree) must write a program to delete the subdirectories and files.

The files in the directory can be deleted by calling the function deletefile, but for special files (read-only, system, hide, etc.) cannot be effectively deleted, and the file properties must be changed to delete. Changing file properties You can use FileSetattr, where the properties of special files are set to normal file properties (0).

Considering that the tree directory structure is best suited for recursive methods, all here uses a recursive algorithm to implement the Deltree function. The following is a specific implementation program.

// path is a directory path that needs to be deleted

// Directory Successfully Remove Returns True, otherwise returns false

Function TFORM1.DELTREE (PATH: STRING): Boolean;

VAR

SearchRec: tsearchrec;

Begin

/ / Judgment if the directory exists

If Directoryexists (PATH) THEN

Begin

// Enter the directory, delete the subdirectory and files

Olddir: = getcurrentdir;

CHDIR (PATH);

/ / Find all any files in the directory

Findfirst ('.', FAANYFILE, SEARCHREC);

Repeat

// Modify the file attribute to a normal attribute value

FileSetAttr (searchRec.name, 0);

// If it is a directory and is not. And .. recursive call Deltree

IF (SearchRec.attr And Fadirectory> 0) THEN

Begin

IF (SearchRec.name [1] <> '.') THEN

IF (not deltree) thein

Break;

end

// If you are the file directly delete

Else

IF (not deletefile (searchrec.name) then

Break;

/ / Continue to find until the end

Until (FindNext (SearchRec) <> 0);

/ / Back to the parent directory, delete the directory

Chdir ('..');

Result: = Removedir (PATH);

SetCurrentDir (Olddir);

end

Else

Result: = FALSE;

END;

This program compiles the passage under Windows 98, Delphi 4.0.

转载请注明原文地址:https://www.9cbs.com/read-1886.html

New Post(0)