在C++中使用popen执行perl命令时出错

Error executing a perl command using popen in C++

本文关键字:perl 命令 出错 执行 popen C++      更新时间:2023-10-16

在我的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");