今天在写C++代码时,遇到一个小问题,也是搞了一下午才解决(惭愧),就是在某个目录下,保存的相同名称的图片没有自动覆盖,意思就是多次运行相同的程序,如果某个文件(名)存在的话,那么这个文件则不会被覆盖,文件还是最早保留的那一文件。
在网上查了下,Window API函数(需要包含头文件include<windows.h>)RemoveDirectory()函数等很多方法只能删除非空目录,可以参考https://blog.csdn.net/weixin_36340947/article/details/77937651
下面是找到的参考代码,亲测有效,一定要注意目录的路径问题,以及删除目录所有文件一定要慎重,可以自己多测试几次,熟悉了之后再使用。
#include<iostream>
#include<string>
#include<io.h>
using namespace std;
//递归删除指定文件夹下所有的文件(目前好像删不了文件夹)
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");
}
直接调用removeDir()函数就行了,输入参数为你要删除的目录的路径(可以为字符串形式),当然可以是相对路径,比如我要删除的目录在工程目录下,路径就可以写成“.\\needRemoveDir”,当然你也可以写成绝对路径,就是下次工程项目换地方的时候需要注意下就可以了。