Reading floats from a binary file

M

Matt McGonigle

Hi all,

Please help me out with this. Perhaps it is a dumb
question, but I can't seem to make it work. I am doing a
file conversion using an unformatted binary file for input
and outputting to a normal text file. I need to read in a
float from the binary file, but it sets my input stream to
failbit. Is there a special way I can read in floats? All
I am doing is

ifstream inFile("input.dta");
float limitValue;

inFile >> limitValue;

to input it. Can someone please tell me how to go about
getting this to work?

Thanks,
Matt
 
E

Eric Twietmeyer

David Lowndes said:
Matt,

What's the format of your file? Is it just a stream of single
precision (32-bit) IEEE floating point values - or something else?

Dave

When using iostream input operator you need to be reading in text versions
of the values. If your file consists of space separated items of the form
"3.14159", etc, then you can use input operator >> to read into a float
variable.

However, you indicate you have a binary file, so presumably your format is
in IEEE (or something, it doesn't matter), but it is not a text
representation. In this case you will need to do "raw" reads from the
stream using the methods "read" or "readsome" of basic_istream. You then
convert (depending on the format of the data in the file) to an IEEE float
and store in your float variable (generally using appropriate casting
operations).

HTH,
Eric Twietmeyer
 
D

David Lowndes

The file is mixed - there are character values, integers,
and float values. It is the output of a test machine, and
has all kinds of information in it, only one subset of
which is a float.

OK, so are you doing the right thing with your code?

Eric is right (I'd missed that aspect), the ifstream operators you're
using will do text conversions rather than direct reads. For example
the following shows writing and reading a binary floating point value:

{
ofstream oFile("input.dta");
float fVal = 123.456f;

oFile.write( (const char *)&fVal, sizeof( fVal ) );
}
{
ifstream inFile("input.dta");
float limitValue;

inFile.read( (char*)&limitValue, sizeof( limitValue ) );
limitValue = limitValue;
}

Dave
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top