/****************************************************************************************************** Treibergs 4-13-6 Gnuplot Driver 1 Program to write data files and execution files that run the plotting software gnuplot from a C program. Thanks to Prof. G. Gustafson for showing me how to do this. drivegnuplo.c ******************************************************************************************************/ # include # include # include double /* Function prototype. */ perfun ( double x, double p ); int main( void ) { double a, b, c, d, p, x; int i; FILE *fp; /* Declaration of file variable */ printf ( "Periodic Function Via Recursive Function Calls\n" ); printf ( " Enter period : " ); scanf ( "%lf", &p ); printf ( " Enter two endpoint values : " ); scanf ( "%lf %lf", &a, &b ); if ( b < a) { /* Swap a and b if b < a. */ c = a; a = b; b = c; } d = ( b - a ) / 300.0; fp = fopen ( "commands.gplot", "w" ); /* Open commands file */ /* fopen returns a pointer to the file. */ /* "w" for writing files, "r" for reading. */ fprintf ( fp, "plot [ %f : %f ] \'fn.dat\' w lines, 0 \n", a - d, b + d ); fprintf ( fp, "pause mouse \n" ); fclose ( fp ); /* closing returns file to system. */ /* Newly written data may be lost without closing the file */ printf ( "\nFunction values from %f to %f are being printed to file \"fn.dat\"\n", a, b ); fp = fopen ( "fn.dat", "w" ); /* Open data file. */ for ( i = 0; i <= 300 ; i++ ) { x = a + i * d; fprintf ( fp, "%25.15f %25.15f\n", x, perfun ( x, p ) ); } fclose( fp ); system("gnuplot commands.gplot"); return EXIT_SUCCESS; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ double perfun ( double x, double p ) { /* perfun grows linearly from 0 to p/4, then droops. */ double result; if ( x < 0.0 ) result = perfun ( x + p, p ); else if ( x >= p ) result = perfun ( x - p, p ); else { if( x <= 0.25*p) result = 16.0 * x / p; else result = 1.0 / ( 0.25 + x / p ) - 1.0; } return result; }