从C+中的管道获取Gnuplot版本+; 在我的C++程序中(Linux),我可以打开一个管道来编写和设置GnUrPro程序的值。 FILE *pipe = NULL; #ifdef WIN32 pipe = _popen("pgnuplot -persist", "w"); #else pipe = popen("gnuplot", "w"); #endif if(pipe == NULL) error("Could not open pipe for write!"); // set title name fprintf(pipe, "set title 'Sample Points' \n");

从C+中的管道获取Gnuplot版本+; 在我的C++程序中(Linux),我可以打开一个管道来编写和设置GnUrPro程序的值。 FILE *pipe = NULL; #ifdef WIN32 pipe = _popen("pgnuplot -persist", "w"); #else pipe = popen("gnuplot", "w"); #endif if(pipe == NULL) error("Could not open pipe for write!"); // set title name fprintf(pipe, "set title 'Sample Points' \n");,c++,gnuplot,C++,Gnuplot,现在我需要得到Gnuplot版本。show version命令执行此操作,但我如何发送此命令,然后读取值。打开管道进行读取对我来说似乎不起作用,代码卡在while循环中而没有获得任何数据 FILE* pipe = popen(command, "r"); if (!pipe) { std::cout << "failed! (can not open pipe)" << endl; return; } char buffer[128]; std::str

现在我需要得到Gnuplot版本。
show version
命令执行此操作,但我如何发送此命令,然后读取值。打开管道进行读取对我来说似乎不起作用,代码卡在while循环中而没有获得任何数据

FILE* pipe = popen(command, "r");
if (!pipe)
{
    std::cout << "failed! (can not open pipe)" << endl;
    return;
}

char buffer[128];
std::string result = "";
while(!feof(pipe))
{
    if(fgets(buffer, 128, pipe) != NULL)
        result += buffer;
}
pclose(pipe);
FILE*pipe=popen(命令“r”);
如果(!管道)
{

std::cout因为在我的Debian/Linux/Sid/x86-64上,命令
gnuplot--version
正在输出到
stdout
以下行:

 gnuplot 5.0 patchlevel 1
我只是建议

FILE* pipversion = popen("gnuplot --version", "r");
if (!pipversion) { perror("popen gnuplot"); exit(EXIT_FAILURE); };
char lineversion[128];
memset (lineversion, 0, sizeof(lineversion));
if (!fgets(lineversion, sizeof(lineversion), pipversion) { 
    perror("fgets"); exit(EXIT_FAILURE);
}
/// lineversion is like: gnuplot 5.0 patchlevel 1
int majvers=0, minvers=0, pos= -1;
char* restvers = NULL;
if (sscanf(lineversion, "gnuplot %d.%d %n", &majvers, &minvers, &pos) >= 2) {
  assert (pos>=0);
  restvers = lineversion+pos;
};
pclose(pipversion);
pipversion = NULL;
之后,
majvers
包含了
gnuplot
的主要版本(如我的例子中的5),而
minvers
包含了次要版本(如0),其中
restvers
是一个后缀字符串(如
不带引号的“patchlevel1”

在异常且不太可能的情况下,可能存在潜在的竞争条件,即在该
popen
和下一个
pipe=popen(“gnuplot”,“w”)之间更新
gnuplot
。顺便说一句,命名一个变量
pipe
的味道很差,因为POSIX和Linux都有系统调用。但是我认为不值得关心这种竞争条件

顺便说一句,您很可能希望用显式的双重调用(后跟适当的&…)来替换第二个
pipe=popen(“gnuplot”,“w”)
,以便将输入和输出管道都连接到
gnuplot
,并在您自己的系统中管理它们(可能在…左右请参阅&答案)

(如果您的应用程序拥有或使用自己的事件循环,特别是如果它是Qt或GTK之上的GUI应用程序,您希望对管道使用相同的事件循环;详细信息特定于提供该事件循环的库:&对于GTK,对于Qt…)


我没有时间详细解释如何做到这一点(在命令+事件循环中使用双管道),但是这本书(在线提供)有几个章节。注意你需要一些事件循环。

你能详细说明不工作的部分吗?它怎么不工作?管道没有打开吗?你得到了意外的结果吗?它没有生成吗?什么?哦,你应该阅读你看到的Di?或者?谢谢你的详细回答!顺便说一句,你忘记在sscanf中设置pos值了