// lecture_18/example.cc: binary file I/O // #include #include #include // define the max line length // #define MAX_LINE_LENGTH 999 // my main program starts here // int main(int argc, char** argv) { // declare a buffer // char buf[MAX_LINE_LENGTH + 1]; // open the file // FILE* fp = fopen(argv[1], "w"); // write a floating-point number // float sum[2] = {27.25, 99.00}; fprintf(stdout, "(write) sum = [%f, %f]\n", sum[0], sum[1]); fprintf(stdout, "the number of elements written was %d\n", fwrite(sum, sizeof(float), 2, fp)); // add an integer // long i = 9; fprintf(stdout, "(write) i = [%d]\n", i); fprintf(stdout, "the number of elements written was %d\n", fwrite(&i, sizeof(long), 1, fp)); // close the file // fclose(fp); /* // open the file for reading // fp = fopen(argv[1], "r"); // read two floating-point numbers // fprintf(stdout, "the number of elements read was %d\n", fread(sum, sizeof(float), 2, fp)); fprintf(stdout, "(read) sum = [%f, %f]\n", sum[0], sum[1]); fprintf(stdout, "the number of elements read was %d\n", fread(&i, sizeof(long), 1, fp)); fprintf(stdout, "(read) i = [%d]\n", i); // close the file // fclose(fp); */ // open the file for reading and seek past the first four bytes // sum[0] = -99999; fp = fopen(argv[1], "r"); fprintf(stdout, "new position = %d\n", fseek(fp, sizeof(float), SEEK_SET)); // read one floating-point number // fprintf(stdout, "the number of elements read was %d\n", fread(sum, sizeof(float), 1, fp)); fprintf(stdout, "(read) sum = [%f]\n", sum[0]); // close the file // fclose(fp); /* // declare a line number counter // long line_num = 0; /* while (fgets(buf, MAX_LINE_LENGTH, fp) != (char*)NULL) { // remove the linefeed // buf[strlen(buf) - 1] = (char)NULL; // print the line // fprintf(stdout, "%3d: %s\n", line_num, buf); // convert these strings to numbers // float val1 = -1, val2 = -1, val3 = -1; sscanf(buf, "%f%f%f", &val1, &val2, &val3); fprintf(stdout, "\t=> %f %f %f\n", val1, val2, val3); // increment the line number // line_num++; } */ /* // loop over the file // long num_read = 0; while ((num_read = fread(buf, sizeof(char), 2, fp)) > 0) { // print the data // fprintf(stdout, "\t=> num_read = %d [%c (%d) %c (%d)]\n", num_read, buf[0], buf[0], buf[1], buf[1]); // clear buf // memset(buf, (int)NULL, 2); } */ /* for (long i = 0; i < 10; i++) { float val = i; fwrite(&val, sizeof(float), 1, fp); } */ /* // loop over the file // long num_read = 0; float newval; while ((num_read = fread(&newval, sizeof(char), 4, fp)) > 0) { // print the data // fprintf(stdout, "\t=> num_read = %d [%f]\n", num_read, newval); } // loop over the file // long num_read = 0; double newval; while ((num_read = fread(&newval, sizeof(char), 8, fp)) > 0) { // print the data // float val1 = *(float*)&newval; float* ptr = (float*)&newval; ptr++; fprintf(stdout, "\t=> num_read = %d [%f %f]\n", num_read, val1, *ptr); } // close the file // fclose(fp); */ // exit gracefully // return 0; }