【发布时间】:2019-11-27 21:57:01
【问题描述】:
所以基本上,我列出了我的临时目录中的所有文件,然后删除它们。显然,有些文件正在使用中,而程序本身正在使用它正在删除的文件。我尝试摆弄SHFileOperation,但没有成功。 (我不知道如何使用它)。如何在删除文件之前检查文件是否正在被另一个程序使用?谢谢!
这给了我错误:fs::remove_all(entry.path());
代码:
#include <iostream>
#include <Windows.h>
#include <filesystem>
#include <lmcons.h>
#include <fileapi.h>
#include "cColors.h"
using namespace std;
namespace fs = filesystem;
char type;
int main()
{
SetConsoleTextAttribute(h, 15);
while (true)
{
cout << "[~] Are you sure you want to run Windows Cleaner? [Y/N]";
cin >> type;
if (type == 'n')
{
break;
exit(0);
}
else if (type == 'y')
{
cout << "[#] Cleaning temp directory\n";
for (const auto& entry : fs::directory_iterator(fs::temp_directory_path()))
{
cout << "[#] Deleting " << entry.path();
fs::remove_all(entry.path()); //This is giving me the error
}
}
else
{
break;
exit(0);
}
}
}
【问题讨论】:
-
如果文件已经打开,您通常无法删除它们。
-
也许您可以将CreateFile 与所需访问权限
0和共享模式OPEN_EXISTING一起使用。然后你必须检查失败的原因。如果没有失败;关闭并删除。 -
How do I find out which process has a file open? 但实际上,这只是引入了另一场 TOCTTOU 比赛。为什么不尝试删除它?系统已经完成了您尝试复制的操作。
-
@JonathanPotter 你可以删除一个正在使用的文件(权限允许),它实际上不会被删除,直到它的所有打开的句柄都被关闭。
标签: c++ winapi delete-file