Good afternoon. I'm a Physical Chemistry undergraduate with little experience on programming. I'm trying to write a program to obtain the Boltzmann distribution using a Monte Carlo method. In summary, for each iteration of a 'for' loop my program generates a matrix which contains quantized values of energy, and the number of particles which occupy each level, then writes the values on a file called "plot.dat", with the energies on the first column (to be plotted as 'x') and number of particles on the second (to be plotted as 'y'). When the file is written, the program request gnuplot to replot the graphic (previously plotted in the beginning using 10 and 999 as initial values for 'x' and 'y', respectively) using the new values, so I can get a graphic output of the physical system status each time an iteration finish (that is to say, a "live plot" of 'plot.dat', which updates every time the file changes). The program works almost like expected, but every 20-30 iterations approx.., gnuplot hangs for about 10 secs, and in the command prompt appears:
gnuplot> plot "auxiliar.dat"
^
line 0: x range is invalid
line 0: warning: Skipping data file with no valid points
Then, the program continues running normally, with gnuplot updating the plot which each iteration until it hangs again. I don't know exactly what is going on, but I suspect gnuplot tries to read the plot.dat file while it's being updated by the program and, in consequence, it fails. Here is a portion of the troubling code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
FILE *plot;
FILE *pipe = popen("gnuplot -persist" , "wt");
plot=fopen("plot.dat", "wt");
fprintf(plot, "10 999\n");
fclose (plot);
fprintf(pipe, "plot %plot.dat%c\n", '"', '"');
int iteration, part1, part2, iteration_msg;
for (iteration = 0; iteration < 110000; iteration++)
{
/* Code of Monte Carlo method here */
/* Update plot.dat with the new values */
fprintf(plot, "%d %d\n", plotdata[fila][1],plotdata[fila][0]);
fclose (plot);
/*Replot plot.dat in gnu after it's updated*/
fprintf(pipe, "replot\n");
}
fclose(pipe);
return 0;
}
Can you help me solving this problem? Thank you in advance. Note: I'm working in Windows.
fclose()on yourplotfile before you are finished with it.gnuplotto plot it before you have written anything to it.