// file: lecture_21/example.cc // #include #include //#include // my main program starts here // int main(int argc, char** argv) { // declare local variables // float sum = 27.272788;; // how great is fprintf() // // float sum1 = 27.0; // float sum2 = 99.0; // fprintf(stdout, "arg 1 = %10.4f %\n", sum1); // open a file // FILE* fp = fopen(argv[1], "w"); if (fp == (FILE*)NULL) { fprintf(stdout, "%s: error opening file (%s)\n", argv[0], argv[1]); return(1); } // print to the file as ASCII // fprintf(stdout, "sum = %10.4f\n", sum); fprintf(fp, "%s %*f ... %s\n", "this is a test", "another test", "%10.4f\n", sum); fprintf(fp, "%10.4f\n", sum); // close the file // if (fp != (FILE*)NULL) { fclose(fp); } /* // open the file for reading // /* FILE* fp_r = fopen(argv[1], "r"); fprintf(stdout, "start file position = %d\n", ftell(fp_r)); fseek(fp_r, (long)0, SEEK_END); fprintf(stdout, "end file position = %d\n", ftell(fp_r)); rewind(fp_r); fprintf(stdout, "start file position = %d\n", ftell(fp_r)); fclose(fp_r); */ /* // read the data // char b1[99], b2[99], b3[99]; float sum_2 = 0.0; fprintf(stdout, "BEFORE: the value of sum_2 is %10.4f\n", sum_2); FILE* fp_r = fopen(argv[1], "r"); fscanf(fp_r, "%s%s%f", b1, b2, &sum_2); //fscanf(stdin, "%s%s%f", b1, b2, &sum_2); fprintf(stdout, "AFTER: the value of sum_2 is (%s) (%s) %10.4f\n", b1, b2,sum_2); fscanf(fp_r, "%*s%*s%f", &sum_2); fprintf(stdout, "AFTER SECOND READ: the value of sum_2 is %10.4f\n", sum_2); fprintf(stdout, "new file position = %d\n", ftell(fp_r)); fclose(fp_r); /* // where are we in the file // fprintf(stdout, "current file position = %d\n", ftell(fp_r)); rewind(fp_r); fprintf(stdout, "current file position = %d\n", ftell(fp_r)); // fscanf(fp_r, "%s%s%s", b1, b2, b3); // fprintf(stdout, "current file position = %d\n", ftell(fp_r)); //sum_2 = atof(b3); // fprintf(stdout, "the value of sum_2 is %10.4f\n", sum_2); // close the file // fclose(fp_r); */ /* // open a file for writing // FILE* fp = fopen(argv[1], "r+"); fseek(fp, (long)0, SEEK_END); // print an array // long N = 3; float a[N] = {1, 2, 3}; for (long i = 0; i < N; i++) { fprintf(fp, "%10.4f ", a[i]); } fprintf(fp, "\n"); // close the file // fclose(fp); */ /* // open a file for reading // FILE* fp_r = fopen(argv[1], "r"); char tmp[999]; fgets(tmp, 999, fp_r); fprintf(stdout, "first line: [%s]", tmp); fgets(tmp, 999, fp_r); fprintf(stdout, "second line: [%s]", tmp); */ /* // read an array // long N = 3; float a[N]; fscanf(fp_r, "%f%f%f", &a[0], &a[1], &a[2]); fprintf(stdout, "\nNew Values:"); for (long i = 0; i < N; i++) { fprintf(stdout, "%10.4f ", a[i]); } fprintf(stdout, "\n"); // close the file // fclose(fp_r); */ // exit gracefully // return 0; }