Plot a function using Gnuplot with C99

Viewed 66

I want to plot the sinus function with Gnuplot using C99 on CLion from JetBrains (Windows 10). I have been given a code that is supposed to work:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void plot(double a, double b, int nbpoints, double (*f)(double)){
    double x, h = (b-a)/nbpoints;
    /* create data file */
    FILE *data = fopen("data.txt", "w");
    for (x = a; x < b+h/2; x+=h)
        fprintf(data, "%g %g\n", x, f(x));
    fclose(data);
    /* create command file */
    FILE *cmd = fopen("cmd.txt", "w");
    fprintf(cmd, "plot 'data.txt' using 1:2 with lines\n");
    fclose(cmd);
    /* execute commands in a file */
    system("gnuplot -persistent cmd.txt");
}

int main() {
    plot(0, M_PI, 100, sin);
}

The interpreter says that "gnuplot" is not recognised. It shows me the same message when I directly write it in the Windows terminal. Yet, I downloaded Gnuplot on my computer, and I also have Octave. Could someone help me to make this work ? Here is the the complete project file on Google Drive in case you would need the additional files of CLion.


EDIT: I have modified the path this way:

system("cd C:\Program Files\gnuplot\bin")

Now, when I enter system("gnuplot") or system("gnuplot.exe"), it opens me another window with gnuplot. Half of my problem is solved. However, I still can't directly write in gnuplot from C, and the command system("gnuplot>plot sin(x)") doesn't work. How could I use the gnuplot terminal without interrupting the code, and make it only pop the plot graph ?

C:\Program Files\gnuplot\bin>gnuplot plot sin(x)

line 0: Cannot load input from 'sin(x)'
^
"plot" line 1: invalid command
1 Answers

The line system("gnuplot -persistent cmd.txt"); has to be replaced by

system("cd C:\\Program Files\\gnuplot\\bin && gnuplot --persist -e plot-sin(x)");

Indeed:

  1. The PATH set was not correct (see 'git' is not recognized as an internal or external command), it had to be redirected to the gnuplot file using the cd command.
  2. It was at first impossible to use the gnuplot interface in one single command line without interrupting the program. The commands as gnuplot plot sin(x) or gnuplot>plot sin(x) didn't work. A look at gnuplot: line 1: invalid command showed me that the --persist -e commands needed to be used:

using '-e' is the same thing as putting the stuff in singe quotes into a temporary file

The --persist makes it so the plot stays on your screen (which you'll want since I doubt you're saving it to a file)

Moreover, a - had to be placed between the plot command and sin(x).

Related