在没有用户输入的情况下从c ++调用gnu plot

时间:2018-06-16 09:16:52

标签: c++ gnuplot popen

我在网上找到了这个代码。它使用来自c ++中生成的数据的gnuplot绘制图表。但是它需要用户输入,如果没有行

,它就无法工作
      printf("press enter to continue...");        
      getchar();

错误消息为

     line 0: warning: Skipping unreadable file "tempData"
     line 0: No data in plot

有人知道解决这个问题吗?我希望在循环中使用此代码,而不是每次都调用输入...

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void plotResults(double* xData, double* yData, int dataSize);
int main() {
int i = 0;
int nIntervals = 100;
double intervalSize = 1.0;
double stepSize = intervalSize/nIntervals;
double* xData = (double*) malloc((nIntervals+1)*sizeof(double));
double* yData = (double*) malloc((nIntervals+1)*sizeof(double));
xData[0] = 0.0;
double x0 = 0.0;
for (i = 0; i < nIntervals; i++) {
    x0 = xData[i];
    xData[i+1] = x0 + stepSize;
}
for (i = 0; i <= nIntervals; i++) {
    x0 = xData[i];
  yData[i] = sin(x0)*cos(10*x0);
}
plotResults(xData,yData,nIntervals);
return 0;
}
void plotResults(double* xData, double* yData, int dataSize) {
FILE *gnuplotPipe,*tempDataFile;
char *tempDataFileName;
double x,y;
int i;
tempDataFileName = "tempData";
gnuplotPipe = popen("gnuplot","w");
if (gnuplotPipe) {
  fprintf(gnuplotPipe,"plot \"%s\" with lines\n",tempDataFileName);
  fflush(gnuplotPipe);
  tempDataFile = fopen(tempDataFileName,"w");
  for (i=0; i <= dataSize; i++) {
      x = xData[i];
      y = yData[i];            
          fprintf(tempDataFile,"%lf %lf\n",x,y);        
      }        
      fclose(tempDataFile);        
      printf("press enter to continue...");        
      getchar();        
      remove(tempDataFileName);        
      fprintf(gnuplotPipe,"exit \n"); 
      pclose(gnuplotPipe);   
  } else {        
      printf("gnuplot not found...");    
  }
} 

1 个答案:

答案 0 :(得分:0)

我认为实际问题是您提前删除了临时文件。我会将代码重组为:

if (gnuplotPipe) 
{
    // Create the temp file
    tempDataFile = fopen(tempDataFileName,"w");
    for (i=0; i <= dataSize; i++) 
    {
        x = xData[i];
        y = yData[i];            
        fprintf(tempDataFile,"%lf %lf\n",x,y);        
    }        
    fclose(tempDataFile);  

    // Send it to gnuplot
    fprintf(gnuplotPipe,"plot \"%s\" with lines\n",tempDataFileName);
    fflush(gnuplotPipe);
    fprintf(gnuplotPipe,"exit \n"); 
    pclose(gnuplotPipe); 

    // Clean up the temp file  
    remove(tempDataFileName);        
} 

然后你不会在你的系统上得到很多临时文件。

另一件好事是让gnuplot持久化,以便在管道关闭后能够看到图表,只需在打开管道时添加-p标志

gnuplotPipe = popen("gnuplot -p","w");