繁体   English   中英

如何使用 boost::process::child 处理路径中的空格?

[英]How to deal with spaces in path using boost::process::child?

我需要执行一个 Windows 批处理脚本。 根据公司政策,我必须为此使用boost::process::child Windows 批处理脚本的路径包含空格(例如C:\\Foo Bar\\batch.bat )。

我正在使用以下代码:

namespace bp = boost::process;
error_code errorCode;
bp::ipstream errorStream;
auto child = bp::child("C:\\Foo Bar\\batch.bat",
    errorCode,
    bp::std_out > bp::null,    // ignore standard output
    bp::std_err > errorStream, // capture standard error
    bp::windows::hide,        // hide window
    bp::shell);               // use shell

  vector<string> errorData;
  string errorLine;

  while (child.running() && getline(errorStream, errorLine) && !errorLine.empty())
  {
    errorData.push_back(errorLine);
  }
  child.wait();

问题是系统 (boost::process) 没有找到路径。 错误消息如下所示:

'C:\\Foo' 不是内部或外部命令,也不是可运行的程序或批处理文件。

我还尝试了以下掩蔽变体:

  • C:\\\\Foo Bar\\\\batch.bat
  • C:\\\\Foo\\ Bar\\\\batch.bat
  • "C:\\\\Foo Bar\\\\batch.bat"
  • C:\\\\Foo~1\\\\batch.bat

如何正确屏蔽空格,以便child()可以正确查找/执行批处理脚本?

"C:\\\\Foo Bar\\\\batch.bat"包装到boost::filesystem::path() ,以便它为您引用字符串:

auto child = bp::child(boost::filesystem::path("C:\\Foo Bar\\batch.bat"),

我建议遵循@Maxim 的回答。

或者,使用反斜杠转义空格:

"C:\\Foo\\ Bar\\batch.bat"
bp::child c(
    bp::exe(boost::filesystem::path("C:\\Foo Bar\\batch.bat").c_str()),
    bp::cmd("options here"), 
    bp::environment(env),       
    bp::std_in.close(),
    bp::std_out > os,
    bp::std_err > es,
    bp::start_dir("workdir here")
);

假设这变成了 Windows CreateProcess 调用,那么应用程序的路径必须用双引号括起来,以便在路径中留出空格。 事实上,建议路径始终用双引号括起来。

所以你会使用:

auto child = bp::child("\"C:\\Foo Bar\\batch.bat\"",

我不知道 Boost::child 是否真的会允许它工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM