C++ recursively delete all files in non-empty directory

       When I was writing C++ code today, I encountered a small problem, and it took an afternoon to solve it (ashamed), that is, in a certain directory, the saved picture with the same name was not automatically overwritten, which means that the same program is run multiple times. If a certain file (name) exists, then this file will not be overwritten, and the file is still the earliest retained file.

      Checked online, Window API function (need to include header file include<windows.h>) RemoveDirectory() function and many other methods can only delete non-empty directories, you can refer to https://blog.csdn.net/weixin_36340947/article /details/77937651

      The following is the reference code found. It is effective for personal testing. You must pay attention to the path of the directory, and you must be careful when deleting all files in the directory. You can test it several times by yourself, and then use it after you are familiar with it.

#include<iostream>
#include<string>
#include<io.h>
using namespace std;

//Recursively delete all files in the specified folder (currently it seems that the folder cannot be deleted)
int removeDir(string dirPath)
{
	struct _finddata_t fb;   //find the storage structure of the same properties file.
	string path;
	long    handle;
	int  resultone;
	int   noFile;            // the tag for the system's hidden files

	noFile = 0;
	handle = 0;

	path = dirPath + "/*";

	handle = _findfirst(path.c_str(), &fb);

	//find the first matching file
	if (handle != -1)
	{
		//find next matching file
		while (0 == _findnext(handle, &fb))
		{
			// "." and ".." are not processed
			noFile = strcmp(fb.name, "..");

			if (0 != noFile)
			{
				path.clear();
				path = dirPath + "/" + fb.name;

				//fb.attrib == 16 means folder
				if (fb.attrib == 16)
				{
					removeDir(path);
				}
				else
				{
					//not folder, delete it. if empty folder, using _rmdir istead.
					remove(path.c_str());
				}
			}
		}
		// close the folder and delete it only if it is closed. For standard c, using closedir instead(findclose -> closedir).
		// when Handle is created, it should be closed at last.  
		_findclose(handle);
	}
	return 0;
}

void main() {
	removeDir(".\\test");
}

      Just call the removeDir() function directly. The input parameter is the path of the directory you want to delete (it can be in the form of a string). Of course, it can be a relative path. For example, the directory I want to delete is in the project directory, and the path can be written as ". \\needRemoveDir", of course, you can also write it as an absolute path, that is, you need to pay attention to it when you change the location of the project next time.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326309276&siteId=291194637