Hi there:

I am trying to output a single variable to a binary file, but couldn't get it done correctly.

result  = 17.0;

     if ((OutFp1 = fopen("myfile.bin", "wb")) == NULL)
     {
        Application->MessageBox("File can't open.", NULL, IDOK);
        return;
     }

     fwrite(&result,sizeof(result), 1, OutFp1);

     fclose(OutFp1);

     if ((InFp15 = fopen("myfile.bin", "rb")) == NULL)
     {
        Application->MessageBox("File can't open.", NULL, IDOK);
        return;
     }

     fread(&rest,sizeof(rest), 1, InFp15);      
     fclose(InFp15);

After 'rest' readed in from the binary file, it equals zero!

Can any one point out where I made mistake?

THank you!

Wrong forum. This is the C++ forum.

Binary I/O is straight-forward, but you need to be aware of certain caveats.

You never list the types of result and rest, but if they are different types then you are playing with fire.

You should also be aware of endianness issues and floating-point format issues, but for this example neither is a problem.

The last issue is fwrite() and fread() take a certain type of pointer.

Make sure you have all these conditions met:

const char* FileName = "myfile.bin";

FILE* OutputFile;
FILE* InputFile;

double OutputValue = 17.0;
double InputValue;

if ((OutputFile = fopen( FileName, "wb" )) == NULL) fooey();
fwrite( (const void*)&OutputValue, sizeof( OutputValue ), 1, OutputFile );
fclose( OutputFile );

if ((InputFile = fopen( FileName, "rb" )) == NULL) fooey();
fread( (void *)&InputValue, sizeof( InputValue ), 1, InputFile );
fclose( InputFile );

if (fabs( InputValue -OutputValue ) > 0.000001) fooey();

As a final note, make sure you use good variable names. Currently what you have is not very illuminating, and anything with a number tacked on the end is usually a bad idea.

A good way to think of it is that variables should be nouns (or noun phrases) and functions should be verbs (or verb phrases).

If this doesn't help, please post a complete example that demonstrates the problem. Good luck!

Thank you very much!

BTW, Result and rest have the same type: double.

This article has been dead for over six months. Start a new discussion instead.