// file: lecture_17/example.cc // #include #include //#include // my main program starts here // int main(int argc, char** argv) { // declare local variables // float sum = 27.272727272; // 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]); } // print to the terminal as ASCII // fprintf(fp, "sum = %10.4f\n", sum); fprintf(fp, "%s ... %s\n", "this is a test", "another test"); // close the file // fclose(fp); // open the file for reading // FILE* fp_r = fopen(argv[1], "r"); fprintf(stdout, "file position = %d\n", ftell(fp_r)); // read the data // char b1[99], b2[99], b3[99]; float sum_2; fscanf(fp_r, "%s%s%f", b1, b2, &sum_2); fprintf(stdout, "the value of sum_2 is %10.4f\n", sum_2); // 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 // 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); // exit gracefully // return 0; }