Click here to Skip to main content
15,894,174 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please can someone explain why I am not getting correct data written in file.... When I try to open the file with Notepad, I don't get value 1.3333 written. I get �ªª? value..... But if I try to write the commented code below in void CFileTestDlg::Write(const void *ptr,unsigned long size), then I get the correct value ABCDEFGHI.
Is there any issue while writing in binary mode? Or is it with type casting float to unsigned char*

void CFileTestDlg::Write(const void *ptr,unsigned long size)
{
    FILE *fp;
    fp=fopen("TestFile.bin","wb");
    char str[50];
   
    fwrite(ptr,size,1,fp);
    fclose(fp);

/*    FILE *fp;
    fp=fopen("test.bin", "wb");
    char x[10]="ABCDEFGHI";
    fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
    fclose(fp);
    */
}

void CFileTestDlg::OnButton1()
{
    // TODO: Add your control notification handler code here

    float buffer=1.33333;
    unsigned char *ptr=NULL;
    Write(&buffer,sizeof(float));           
}
Posted
Updated 13-Mar-10 8:31am
v2

The issue is that you are writing in binary mode. Notepad is reading in text mode, so the binary bytes that make up the binary storage version to the float value don't translate.

try converting the float to characters first:

float buffer = 1.33333;
char* str[11];
sprintf(str,"%10.5f",buffer);

then write it to the file as text as you did in your commented out code.
Note that the format string will limit both size and precision, so you should insure that the size of the character array allocated and the format string are both satisfactory...
 
Share this answer
 
You should go back to your C++ documentation and read up on basic types, casting and IO. If you write a float value to a file, then you must read it back as a float value. It will not magically get translated into text.
 
Share this answer
 
v3
Your result is correct,
These are bytes from your float.

In a binary file, that is not created to be shown by Notepad... :)

Try to read the dump back to a float and you will get the 1.33333 again (not "1.33333") :)

When you will want to read "1.33333" in the Notepad -
just convert the float to char sequence firstly :)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900