// file: example.cc // // generate a sinewave to a file // // include files // #include "example.h" // main program // int main(int argc, char** argv) { // check the number of command line arguments // if (argc < NARGS) { fprintf(stdout, "**> insufficient number of arguments (%d)\n", argc); return(-1); } // get the command line arguments // FILE* fp = fopen(argv[1], "w"); if (fp == (FILE*)NULL) { fprintf(stdout, "error opening file\n"); return(-1); } float frequency = atof(argv[2]); fprintf(stdout, "frequency = %f Hz\n", frequency); float sample_frequency = atof(argv[3]); fprintf(stdout, "sample_frequency = %f Hz\n", sample_frequency); float total_time = atof(argv[4]); fprintf(stdout, "total time = %f Hz\n", total_time); float amplitude = atof(argv[5]); fprintf(stdout, "amplitude = %f Hz\n", amplitude); // convert time to samples // long N = (long)round(total_time * sample_frequency); fprintf(stdout, "the number of samples is %d\n", N); // loop over the samples and generate a sinewave // // for (float ctime = 0; ctime < total_time; ctime += 1.0 / sample_frequency) { for (long i = 0; i < N; i++) { // calculate a value // // fprintf(stdout, "(%d) (%f secs): %f\n", i, (float)i / sample_frequency, sum); float sum = amplitude * sin(2.0 * M_PI * frequency * (float)i / sample_frequency); // write this to a file // short int ival = (short int)round(SCALE * sum); fprintf(stdout, "(%d) (%f secs): %f (%d)\n", i, (float)i / sample_frequency, sum, ival); if (fwrite(&ival, sizeof(short int), 1, fp) != 1) { fprintf(stdout, "*> error writing data (%d %d)\n", i, ival); } } // close the file // fclose(fp); // open the file again // FILE* fp2 = fopen(argv[1], "r"); if (fp2 == (FILE*)NULL) { fprintf(stdout, "error opening file\n"); return(-1); } fprintf(stdout, "... reading back ...\n"); long i = 0; short int ival; while (fread(&ival, sizeof(short int), 1, fp2) == 1) { fprintf(stdout, "(%d) (%f secs): %f (%d)\n", i, (float)i / sample_frequency, (float)ival, ival); i++; } // exit gracefully // return 0; }