在C++中使用popen执行perl命令时出错
Error executing a perl command using popen in C++
在我的c++程序中,我想执行一个perl命令并读取执行返回的输出。我使用popen,但在执行命令时出错:
命令:
string cmd = "perl -ne 's/^\S+\s//; if ((/" +
pattern1+ " START/ .. /" + pattern2+ " END/) && /find/)"
" { print "$_"}' file";
stream = popen(cmd.c_str(),"r");
如果我在命令行中执行这个命令,它会起作用,但在C++中,我会得到这个错误:
Search pattern not terminated at -e line 1.
在命令行中工作的命令是,在C++中,我已经转义了"\"answers":
perl -ne 's/^\S+\s//; if ((/aaa START/ .. /bbb END/) && /find/) { print "$_"}' file
如果我执行这个命令,它就会工作:"perl-ne-print$_file"。但我最初的命令没有。我做错了什么。谢谢
这是您的转义符。当
\
变成时,您必须在C++字符串中将它们加倍。然后shell执行它的处理,正如您在命令行中看到的那样。即另一轮CCD_ 4变为CCD_。
您需要转义反斜杠(通过添加更多反斜杠!)。
std::string cmd = "perl -ne 's/^\\S+\\s//; if ((/" +
pattern1 + " START/ .. /" +
pattern2+ " END/) && /find/)"
" { print "$_"}' file";
在C++0x中,可以使用原始R"(strings)"
来避免添加斜杠。使用类似的GCC编译
g++ -std=c++0x -Wall popen.cpp
示例:
std::string cmd_raw = R"(perl -ne 's/^\S+\s//; if ((/)" +
pattern1 + R"( START/ .. /)" +
pattern2 + R"( END/) && /find/))"
R"( { print "$_"}' file)";
这很有效:
cmd = "perl -ne 's/^\\S+\\s//; if ((/" +
pattern1+ " START/ .. /" + pattern2+ " END/) && /find/)"
" { print "$_"}' file";
stream = popen(cmd.c_str(),"r");
相关文章:
- 从命令行c++发送文本文件名
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 使用QProcess执行命令,并将结果存储在QStringList中
- 数组长度,为什么从命令行获取时不能使用它?
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- clang整洁10忽略了我的NOLINT命令
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- 如何处理linux终端中带有负号(-)的C++中的命令行参数
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- 使用VS Code和CMake Tools运行自定义命令
- 如何使用ESP8266向谷歌主页发送命令
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 通过 Openssl 命令行加密,通过 c++ 解密
- CMake "--target install"无需"--build"命令行
- Gstreamer 管道从命令 lne 到 c 代码
- 自动"yes"到 Popen SSH 命令
- 在C++中使用popen执行perl命令时出错