#include #include // You need to help C by separating floats... void format_carefully() { FILE * fp; fp = fopen("tmp", "w"); fprintf( fp, "%f%f", 1.0,2.0 ); fclose(fp); fp = fopen("tmp", "r"); float a, b; fscanf( fp, "%f%f", &a, &b ); printf( "a = %f, b = %f\n", a, b ); fclose(fp); } void mix_text_binary( char *filename ) { FILE * fp; fp = fopen(filename, "w"); if (fp == NULL) { printf( "Something went wrong attempting to open %s\n", filename ); return; } double a = 1.2345e-3/7.0; fprintf( fp, "%0.20lf,", a ); fwrite( &a, sizeof(double), 1, fp ); fclose( fp ); fp = fopen( filename, "r" ); if (fp == NULL) { printf( "Something went wrong attempting to open %s\n", filename ); return; } double b; fscanf( fp, "%lf,", &b ); double c; fread( &c, sizeof(double), 1, fp ); printf( "read in %0.8f and %0.8f\n", b, c ); printf( "difference is %e\n", b-c ); fclose(fp); } void test_endian() { unsigned int a = 1; FILE *fp = fopen( "short", "w" ); fwrite( &a, sizeof(unsigned int), 1, fp ); fclose(fp); } typedef struct C3 { char a; char b; char c; } C3; void test_structs() { C3 *arr = malloc( sizeof(C3) * 3 ); printf( "sizeof C3 %d\n", sizeof(C3) ); for (int i = 0; i < 3; i++) { arr[i].a = 'a'; arr[i].b = 'b'; arr[i].c = 'c'; } FILE *fp = fopen( "structs", "w" ); fwrite( arr, sizeof(C3), 3, fp ); fclose(fp); fp = fopen( "structs", "r" ); fread( arr, sizeof(C3)*3, 1, fp ); fclose( fp ); for (int i =0; i < 3; i++) printf( "%c %c %c\n", arr[i].a, arr[i].b, arr[i].c ); } int main(int argc, char* argv[]) { //format_carefully(); //test_endian(); test_structs(); //if (argc <= 1) { // printf( "Usage: ./compare_io \n" ); // printf( " where is the name of a file that will be written to and then read from\n" ); // return 1; //} //mix_text_binary( argv[1] ); return 0; }