2

I'm writing a code in c++ which plots a dataset using gnuplot, and I realized that I could simplify my code a lot if I could get variables from gnuplot to my c++ code. e.g. if I did a fit f and get his stats i.e.

f(x)=a*x+b
fit f 'data.txt' via a,b
stats 'data.txt' u (f($1)):2 name 'Sf'

Is there any way to get, for example, the Sf_records and save it to a variable in my code? Like int N = Rf_records?

Thanks for your help

  • You could simply pipe the gnuplot output to a file, then read and parse it in your C++ code to extract the values. – Sedenion Apr 18 '22 at 06:49

1 Answers1

2

Assuming that you are communicating with gnuplot trougth a FIFO, you can order to gnuplot

print <variable>

and you can read this to your c++ program.

Eg. for reading a varirable:

double getVal(std::string val){
  
  float ret;
  std::string str;
  
  str="print "; str+=val;str+="\n";
  
  fprintf(gp, str.c_str());
  fflush(gp);
  
  fscanf(gpin, "%f", &ret);
  
  return ret;
}

To open a gnuplot FIFO

void connecttognuplot(){
  
    //make an unique FIFO
    std::stringstream alma; alma.str(std::string()); alma<<std::clock(); GPFIFO="./gpio"+alma.str();
  
    //gnuplot => program FIFO
    if (mkfifo(GPFIFO.c_str(), 0600)) {
    if (errno != EEXIST) {
        perror(GPFIFO.c_str());
        unlink(GPFIFO.c_str());
    }
    }
    // For fprintf
    if (NULL == (gp = popen("gnuplot 2> /tmp/gp1","w"))) {
    perror("gnuplot");
    pclose(gp);
    }

    //  Redirect print
    fprintf(gp, "set print \"%s\";\n", GPFIFO.c_str());
    fflush(gp);

    // For fscanf
    if (NULL == (gpin = fopen(GPFIFO.c_str(),"r"))) {
    perror(GPFIFO.c_str());
    pclose(gp);
    }
  
  }
Tom Solid
  • 2,226
  • 1
  • 13
  • 32