Joseph Suprenant wrote:
Hello all,
I have a C++ program, it does some calculations on things and then
prints out a file in the format in which GNUPLOT can use. So my question is
how would i call GNUPLOT from my C++ program. I know in some operating
systems you can do system("gnuplot");
system is useless since then you can't pass any commands to GNUplot
But not with red hat 7.3. So could
some kind soul help me out? After it starts up GNUPLOT my program will
terminate.
I've done this on Linux using the popen() function (which is not
standard C++, but POSIX-standard)
class GNUplot {
public:
GNUplot() throw(string);
~GNUplot();
void operator ()(const string& command);
// send any command to gnuplot
protected:
FILE *gnuplotpipe;
};
GNUplot::GNUplot() throw(string) {
gnuplotpipe=popen("gnuplot","w");
if (!gnuplotpipe) {
throw("Gnuplot not found !");
}
}
GNUplot::~GNUplot() {
fprintf(gnuplotpipe,"exit\n");
pclose(gnuplotpipe);
}
void GNUplot::operator() (const string& command) {
fprintf(gnuplotpipe,"%s\n",command.c_str());
fflush(gnuplotpipe);
// flush is necessary, nothing gets plotted else
};
You simply construct one object and invoke it with operator () like
GNUplot plotter;
plotter("plot sin(x)");
Note that GNUplot will be killed as soon as your program terminates. So
you need to wait for keystroke or similar, otherwise you will only see
short flashing of the graph. If you need that the graph window stays on
screen after your pragram fnished, then instead of "gnuplot" in the
constructor invoke "gnuplot -persist".
--
Vale !
Christianus Auriocus