You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

system函数无法执行含空格路径的.exe程序问题求助

含空格路径的.exe通过system()执行失败

我想让程序执行一个路径中包含空格的.exe文件(用户名带空格),写了下面的C++代码,但执行失败:

#include<iostream>
#include<filesystem>

int main()
{
    std::filesystem::path current_path = std::filesystem::current_path();
    std::cout << "called from origin file!" << std::endl;

    std::string string_current_path = current_path.u8string();
    string_current_path = string_current_path + "\\print.exe";

    string_current_path = std::string(string_current_path);
    const char * command = string_current_path.c_str();

    std::cout <<command<< std::endl;
    system(command);
    return 0;
}

执行后输出如下:

called from origin file!
C:\Users\Nair PC\Desktop\innerfall(versionV2)\print.exe
"C:\Users\Nair" is not valid member of command or executing programm

解决方法

问题根源是system()会把空格当成命令与参数的分隔符,导致系统误将C:\Users\Nair识别为命令,后续内容被当成无效参数。

只需给完整路径加上双引号,让系统把带空格的路径视为一个整体即可。修改代码中路径拼接的部分:

方式一:直接拼接引号

// 拼接路径时前后加上双引号
string_current_path = "\"" + current_path.u8string() + "\\print.exe\"";

方式二:结合std::filesystem更规范处理

std::filesystem::path exe_path = current_path / "print.exe";
// 给路径套上双引号
std::string command = "\"" + exe_path.u8string() + "\"";
system(command.c_str());

修改后,system()收到的命令会是带双引号的完整路径,就能正确定位并执行目标exe文件了。


内容的提问来源于stack exchange,提问作者Nair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 19:22:34