可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am trying to plot graphs using GNUPLOT
which is a command line interface. But I need to integrate it in c program, so that if program gets executed, graph is plotted. This can be done by using popen
command. I have made a code where I am doing popen("gnuplot","r")
so now when I execute the program, gnuplot starts. But I need to send multiple commands like popen("sin(x)","r")
after popen("gnuplot","r")
so that a sin graph is plotted when I execute the code. But i dont know how to pass multiple commands.Please tell me how can I pass multiple commands using popen
.Please help thanks?
Here is the code which I am using to send single command:
#include <stdio.h> int main() { FILE *fp; int status; fp = popen("gnuplot","r"); pclose(fp); return 0; }
回答1:
Once you have called popen(), your file descriptor 'fp' is open and allows you to write data through it which the gnuplot command will see as input. Note that the type should be what you want to do with the pipe, not what the command will do with it, so you should use 'w' since you want to write. And you can issue multiple commands in sequence until you're done.
For example:
#include <stdio.h> int main() { FILE *fp; int status; fp = popen("gnuplot","w"); fprintf(fp, "plot sin(x)\n"); fprintf(fp, "plot tan(x)\n"); pclose(fp); return 0; }
Will send "sin(x)" and "tan(x)" followed by newlines through the pipe where gnuplot can read it as input.
回答2:
You should write, not read, to gnuplot
, so try:
FILE *fp = popen("gnuplot","w"); if (!fp) { perror("popen gnuplot"); exit(EXIT_FAILURE); }; fprintf(fp, "plot sin(x)/x\n"); fflush(fp);
Don't forget to pclose(fp)
where you are done. But this will probably close the plotted graph. See the §7.8 question of gnuplot FAQ