writing to file as float

Hi

I would like to write out to a file , float values, so that I can read it back in this way. How can I write it out to file as float. I have tried writing it out previously, but i can do it as char (and read it back as char).

outFile <<isInShape(x,y,z); //this writes out as char

How about for floats?

-------

this is how i want to read it in:

FILE *fp = fopen(filename, "rb");
float *data=(float*) malloc(size);
size_t read = fread(data, 1, size, fp);
fclose(fp);
LuckyLucksAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

frankhelkCommented:
You could write mostly the same way you want to read ... use fwrite():

float fl = 99;
FILE *fp = fopen(filename, "rb");
size_t read = fwrite(data, sizeof(float), 1, &fl);
fclose(fp); 

Open in new window


If your file is to contain mor than a single float, i.e. one or more struct objects, you'll have to ensure proper packing for compatibility between platforms. Enclose the struct definitions into a #pragma pack(1) directive to ensure tight packing.
0
sarabandeCommented:
in c++ you wouldn't use fread, fwrite and malloc bit std::ifstream::read, std::ofstream::write and operator new.

the std::ofstream::write wants a char buffer (char array or pointer to char arrray) as first argument. you would cast a pointer to float to char* what is safe since you also pass the size of the buffer as second argument.

float fl = 99.99;
std::ofstream outfile("outfile.dat", std::ios::binary | std::ios::out);
outfile.write((const char*)&fl, sizeof(fl));
outfile.close();

Open in new window


Sara
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sarabandeCommented:
you'll have to ensure proper packing for compatibility between platforms. Enclose the struct definitions into a #pragma pack(1) directive
since #pragma pack is a proprietary microsoft preprocessor command, it hardly makes sense to use it for portability purposes. in general you better do the packing by setting appropriate project properties rather than by preprocessor directives in the source files.

also a single float or an array of float are automatically packed. packing only is an issue if using structures between platforms but then there are more things to consider than packing. for example, in c/c++ the binary bit representation of a float is not standardized and can differ especially if endianess is not the same.

if file size is not a matter you may consider to store floating point numbers as strings. beside of portability benefits you also would avoid formatting issues which may occur  since conversion of floats from binary to decimal is ambiguous, for example 1.99999... and 2.000... mathematically is the same number but with floats you have a whole range of bit representations which all would round up to 2.0000 but are different.

Sara
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

frankhelkCommented:
As I worte, packing needs to be looked at when dealing with structures, ... in that aspect I'm with you.

I admit that #pragma pack is MS specific, and that I forgot to mention that the problem might occur on other environments, too and needs to be handled with the respective equivalents of #pragma pack. Besides of that, packing everything (when avised so by project settings) might impact performance or lead to exceptions.

Storing the float vaues as strings is ...  questionable. There might be scenarios where that could lead to different results while not (visibly and willingly) changing the input.

Consider some kind of calculating table like Excel ... you put in some values, and some formulas calculate results. When saving the table, the values are stored as strings. In that case some precision might get lost, and after loading the table and doing a recalc, the result might have changed due to rounding differences. To prevent that, you have to store the floats in a format that holds more decimal places than the binary format ever could.
0
sarabandeCommented:
yes, intermediate numbers calculated always should have best precision. but would you store those values? the numbers always could be recalculated without loss. so storing those values actually is not recommended and even if you do, say in a report, you wouldn't use these numbers for further calculations but only for showing  them as strings. furthermore, a float number only has a precision of six to 9 decimal digits. since input numbers normally are strings - as in the excel - any conversion to binary float numbers would mean a loss and not a gain of precision. so if you have fixed decimal places for your numbers, you better would turn them to integers to get maximum precision and maximum speed. only for division or exponential operations, float or double have to be used, but rarely stored then.

Sara
0
frankhelkCommented:
If it's only storing the intermediates, you're right. But if one inputs many digits as input constant (still fitting into the float, but too much for the storing string) the initial calculation would differ from the the calculation after store/reload.

Not a common scenario - sure - but worth keeping in mind when doing such storage conversions.

BTW: As you lined out any number with more than 9 digits would loose precision when it's stored in float ... but then the remaining needed precision would be to the extent of float. If that is stored i.e. into a 0.0000000E+000 string, further precision is lost and the results could differ.

P.S.: I reffered to fread, fwrtite, etc. because the author preferred that family of functions for reading the data and seemed to be familiar with 'em. Surely the usage of their modern c++ equivalents is to be recommended ...
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.