views:

95

answers:

2

Hi,

I'm trying to read 4-byte numbers stored in a binary file, but I don't seem to be getting the correct output. Here's my code:

#include <stdio.h>
#include <stdlib.h>

int main ()
 {
  int res;
  FILE *file;
  float v;

  //Open file
  file = fopen("prj3.dat", "rb");
  if (!file)
  {
   printf("Unable to open file input.dat\n");
  }
  else
  {
   res = fread(&v, sizeof(v), 1, file);
   if(res==-1)
   {
    printf("Unable to open file input.dat\n");
   }
   else
   {
    printf("v = %f\n", v);
   }
  }

  return;
 }

My output is v = -961576900.0000000, but it should be v = 3.14159. Any ideas as to where my problem is?

NB. input.dat is the binary file: 11010000 00001111 01001001 01000000

Thanks

+4  A: 

Make sure fread returned the same value of sizeof(float), which is the size you are reading. Also make sure your file cursor is in the correct location, otherwise use fseek. Finally, was your file written in a big-endian machine? Was it saved correctly? The code seems ok for me.

Andres
Thanks - turns out the file was written on a little-endian machine, but was being read as big-endian.
Ben
A: 

In addition, you should be fclose(file) also. As for the float, floats are implementation defined.

Would you not consider doing it this way using format specifiers such as in the example below:

printf("%8.2f\n",v);  

This formats the value of v to be 8 places and 2 decimal places after the period thereby rounding the float number to your expected output. It seems to me, that the binary file was written on a big-endian platform. Look here for how to do this and read here on this about endianess business.

Write a small program to test the endianess on the originating system where the binary file was created on and run it on your machine and check the results.

Hope this helps, Best regards, Tom.

tommieb75