Gnuplot,来自windows的C++。命令窗口打开和关闭
问题描述:
我有以下内容,无论我尝试命令窗口是否打开并再次关闭。没有绘图,没有文件被写入。任何有解决方案的人都可以使用C++的gnuplot。我有4.4和4.6rc1可用。Gnuplot,来自windows的C++。命令窗口打开和关闭
#ifdef WIN32
gp = _popen("C:\Program Files (x86)\gnuplot\bin\pgnuplot.exe", "w");
#else
gp = popen("gnuplot -persist", "w");
#endif
if (gp == NULL)
return -1;
/* fprintf(gp, "unset border\n");
fprintf(gp, "set clip\n");
fprintf(gp, "set polar\n");
fprintf(gp, "set xtics axis nomirror\n");
fprintf(gp, "set ytics axis nomirror\n");
fprintf(gp, "unset rtics\n");
fprintf(gp, "set samples 160\n");
fprintf(gp, "set zeroaxis");
fprintf(gp, " set trange [0:2*pi]");*/
fprintf(gp, "set term png\n");
fprintf(gp, "set output \"c:\\printme.png\"");
fprintf(gp, "plot .5,1,1.5\n");
fprintf(gp, "pause -1\n");
fflush(gp);
答
下面的程序在Windows上使用Visual Studio和MinGW编译器进行了测试,以及GNU/Linux上使用gcc
。必须使用gnuplot
二进制文件,并且在Windows上,必须使用管道版本的二进制文件。
我发现Windows管道比GNU/Linux上相应的管道慢得多。对于大型数据集,通过Windows上的管道将数据传输到gnuplot
的速度很慢并且通常不可靠。此外,按键等待代码在GNU/Linux上更有用,其中一旦调用pclose()
,绘图窗口将关闭。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
// Tested on:
// 1. Visual Studio 2012 on Windows
// 2. Mingw gcc 4.7.1 on Windows
// 3. gcc 4.6.3 on GNU/Linux
// Note that gnuplot binary must be on the path
// and on Windows we need to use the piped version of gnuplot
#ifdef WIN32
#define GNUPLOT_NAME "pgnuplot -persist"
#else
#define GNUPLOT_NAME "gnuplot"
#endif
int main()
{
#ifdef WIN32
FILE *pipe = _popen(GNUPLOT_NAME, "w");
#else
FILE *pipe = popen(GNUPLOT_NAME, "w");
#endif
if (pipe != NULL)
{
fprintf(pipe, "set term wx\n"); // set the terminal
fprintf(pipe, "plot '-' with lines\n"); // plot type
for(int i = 0; i < 10; i++) // loop over the data [0,...,9]
fprintf(pipe, "%d\n", i); // data terminated with \n
fprintf(pipe, "%s\n", "e"); // termination character
fflush(pipe); // flush the pipe
// wait for key press
std::cin.clear();
std::cin.ignore(std::cin.rdbuf()->in_avail());
std::cin.get();
#ifdef WIN32
_pclose(pipe);
#else
pclose(pipe);
#endif
}
else
std::cout << "Could not open pipe" << std::endl;
return 0;
}
答
当然,以下的答案颇为相似尼古拉斯Kinar的答案,只增加一点就是如何正确保存.png
文件。还有一些建议:
- 如果输入路径有空格,它将不起作用。在使用Visual Studio 2013的Windows 8中,它显示错误
"C:Program" is not recognized as an internal or external command....
- 如果您没有提及任何输出路径,它将打印并保存在C++程序本身的目录中。所以你必须检查输出路径的正确格式,因为
gnuplot
没有显示任何错误,所以很难找出确切的原因。
下面是完整的C++程序,为什么不写你的命令文件,然后使用该脚本运行的gnuplot在Windows 8.1
#include <cstdio>
#include <iostream>
int main()
{
FILE* pipe = _popen("C:/gnuplot/bin/pgnuplot.exe", "w");
if (pipe != NULL)
{
fprintf(pipe, "set term win\n");
fprintf(pipe, "plot(x, sin(x))\n"); //a simple example function
fprintf(pipe, "set term pngcairo\n");
fprintf(pipe, "set output \"myFile.png\"\n");
fprintf(pipe, "replot\n");
fprintf(pipe, "set term win\n");
fflush(pipe);
}
else puts("Could not open the file\n");
_pclose(pipe);
//system("pause");
return 0;
}
作品只是罚款的Visual Studio 2013? – JRG 2012-02-20 17:00:43
现在这样做,但真的很喜欢从我的应用程序向用户显示直方图。 – 2012-02-20 17:53:45