/* Program to show correct storage of floating data by binary i-o */ #include #include #include main() { float d, e; FILE *f; size_t num_written, num_read; d = sqrt(2.0); f = fopen("tempfile.dat", "wb"); /* NB: "wb" means "write binary" */ if (f == NULL) { fprintf(stderr, "Failed to open output file\n"); exit(EXIT_FAILURE); } num_written = fwrite(&d, sizeof(float), 1, f); if (num_written < 1) { fprintf(stderr, "Data not written\n"); fclose(f); exit(EXIT_FAILURE); } fclose(f); f = fopen("tempfile.dat", "rb"); /* NB: "rb" means "read binary" */ if (f == NULL) { fprintf(stderr, "Failed to open input file\n"); exit(EXIT_FAILURE); } num_read = fread(&e, sizeof(float), 1, f); if (num_read< 1) { fprintf(stderr, "Data not read\n"); exit(EXIT_FAILURE); } fclose(f); printf("%f is ", d); if (d != e) { printf("NOT "); } printf("equal to %f\n", e); return 0; }