Author Topic: Reading Floats from file Streams (C++)  (Read 4164 times)

Alhexx

  • *
  • Posts: 1894
    • View Profile
    • http://www.alhexx.com
Reading Floats from file Streams (C++)
« on: 2002-04-12 17:01:00 »
I'm workin' with a FILE type and I've used functions like fgetc, fgetw and so on to read out integers.
But how the heck can I read out a IEEE float from a binary file stream under C++ ? :-?

BTW: I'm programmin' with Win32 API, no MFC ...

 - Alhexx

Alhexx

  • *
  • Posts: 1894
    • View Profile
    • http://www.alhexx.com
Reading Floats from file Streams (C++)
« Reply #1 on: 2002-04-12 17:08:00 »
Hm ... could this be useful?
Code: [Select]

ifstream inFile( "junk" );        // open the input file
if ( !inFile.is_open() )
{
cout << "I can't open 'junk'";
    return 2;
}

int x;
float y;
double z;

fread( (char *) &x, sizeof( x ), 1, inFile ); // read an int
fread( (char *) &y, sizeof( y ), 1, inFile ); // read a float (4-byte)
fread( (char *) &z, sizeof( z ), 1, inFile ); // read a double

ofstream oFile( "crud" );          // don't forget to check that it opened
if ( !inFile.is_open() )
{
cout << "I can't open 'crud'";
    return 2;
}

oFile.write( (char *) &z, sizeof( z ) ); // write a double value (in binary)
oFile.close();
inFile.close();



I'll try it out :D

 - Alhexx

mirex

  • *
  • Posts: 1645
    • View Profile
    • http://mirex.mypage.sk
Reading Floats from file Streams (C++)
« Reply #2 on: 2002-04-15 11:37:00 »
Should work. But i never used that 'ifstream' thingy. This is the way how i use it, and it works in both dos and win.

FILE *fin;
float f;

fin = fopen( "this.one", "rb" );  //rb means read-binary
if ( fin != NULL ) {
  fread( &f, 1, 4, fin );  //size of float = 4 bytes
  fclose( fin );
}

Alhexx

  • *
  • Posts: 1894
    • View Profile
    • http://www.alhexx.com
Reading Floats from file Streams (C++)
« Reply #3 on: 2002-04-15 16:20:00 »
Yes, I don't use it, too. This was just a source I found on the web.

 - Alhexx