Windows C++ 删除带空格文件夹

环境: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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值