环境:Win10,VS2015
注意:路径一定要添加双引号,否则删除失败 !!!
代码:
#include <iostream>
#include <Windows.h>
bool RunCommand(const std::string& command)
{
bool res = false;
//创建进程
STARTUPINFO si = { sizeof(STARTUPINFO) };//在产生子进程时,子进程的窗口相关信息
PROCESS_INFORMATION pi; //子进程的ID/线程相关信息
USES_CONVERSION_EX;
LPWSTR commandLine = A2W_EX(command.c_str(), command.length());
BOOL bRet = CreateProcess( //调用失败,返回0;调用成功返回非0;
NULL, //一般都是空;(另一种批处理情况:此参数指定"cmd.exe",下一个命令行参数 "/c otherBatFile")
commandLine, //命令行参数
NULL, //_In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes,
NULL, //_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
FALSE, //_In_ BOOL bInheritHandles,
CREATE_NO_WINDOW, //不显示窗口。
NULL, //_In_opt_ LPVOID lpEnvironment,
NULL, //_In_opt_ LPCTSTR lpCurrentDirectory,
&si, //_In_ LPSTARTUPINFO lpStartupInfo,
&pi); //_Out_ LPPROCESS_INFORMATION lpProcessInformation
if (bRet)
{
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD returnCode;//用于保存子程进的返回值,执行成功返回0,失败非0;
GetExitCodeProcess(pi.hProcess, &returnCode);
if (!returnCode)
{
res = true;
}
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
return res;
}
//删除文件夹
void RemoveFolder(std::string directoryPath)
{
std::string tmpDirectoryPath = AddDoubleQuotations(directoryPath);
std::string cmdStr("/C rmdir /S /Q ");
cmdStr.append(directoryPath);
RunCommand(cmdStr);
}
//路径添加双引号
std::string AddDoubleQuotations(std::string value)
{
return '\"' + value + '\"';
}
int main()
{
std::string path = "C:\\Users\\think\\Desktop\\A B C";
path = AddDoubleQuotations(path);
RemoveFolder(path);
return 0;
}