11:04:06 PM Oct 27
It is nice to visualize data in a C program with Gnuplot. This wrapper does exactly it. Please refer to this article for the idea.
gnuplot.h
FILE *
void);
init_gp(
void
FILE * output);
close_gp(
void
FILE * stream, char * command); write_gp(
gnuplot.c
#include <stdio.h>
#include <stdlib.h>
FILE *
void)
init_gp(
{/* Create a pipe for gnuplot... */
FILE * output;
"gnuplot", "w");
output = popen (
/* Check if open correctly */
if (!output)
{"Gnuplot failed to open!!!\n");
fprintf (stderr,
exit (EXIT_FAILURE);
}
return output;
}
void
FILE * output)
close_gp(
{if (pclose (output) != 0)
{
fprintf (stderr,"...Error was encountered in running Gnuplot!!!\n");
exit (EXIT_FAILURE);
}
}
void
FILE * stream, char * command)
write_gp(
{"%s\n", command);
fprintf (stream,
fflush (stream);
if (ferror (stream))
{"...Output to stream failed!!!\n");
fprintf (stderr,
exit (EXIT_FAILURE);
}
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include "gnuplot.h"
#define GP(CMD) write_gp(gp, CMD)
int
void)
main (
{/* Initialize Gnuplot... */
FILE * gp = init_gp();
/* Seed the random number */
0);
srand(
/* Generate 500 random numbers ranging from -100 to 100... */
int len = 500;
int randoms [len];
for (int i = 0 ; i < len; ++i)
{200 - 100;
randoms[i] = rand() %
}
/* Data-driven plotting... */
"plot '-' using 1:2 with linespoints pointsize 2 linewidth 0.25 linecolor rgb 'blue',\\");
GP("");
GP(
for (int i = 0; i < len; ++i)
{char cmd [100];
"%d %d", i, randoms[i]);
sprintf(cmd,
GP(cmd);
}"e");
GP(
/* Displaying Gnuplot window until any key press is accepted... */
char anykey[2];
"Press any key to exit...");
printf(2, stdin);
fgets(anykey,
/* Terminate Gnuplot... */
// write_gp(gp, "exit");
"exit");
GP(
close_gp(gp);
return EXIT_SUCCESS;
}