David Hitchcock
David Hitchcock

Reputation: 23

Problems saving float array to binary file and reading back (C++)

I am trying to simply write an array of float values to a file and then read it back.
I have tried writing it directly from an array, but when reading it back I keep hitting a problem for arrays with length greater than 153. The code example writes each float value one by one for clarity.

For values with index greater than or equal to 153 they have the value 153.0, where they should be 153.0, 154.0, 155.0, ...

Why doesn't this code work for me?

  int length = 160;

  char* fileName = "testFile.dat";

  // Write data to file

  FILE* file = fopen (fileName, "w");

  for(int i = 0; i< length; i++){
    // We are just storing the indices, so value at i is equal to i
    float f = (float) i;
    fwrite(&f, sizeof(float), 1, file);
  }

  fclose(file);

  // Read data from file into results array

  file = fopen(fileName, "r");

  float* results = new float[length];

  for(int i = 0; i< length; i++){
    float f;
    fread(&f, sizeof(float), 1, file);
    results[i] = f;
  }

  fclose(file);

  // Now check data in results array

  bool fail = false;

  for(int i = 0; i< length; i++){
    if(results[i]!=(float)i){
      fail = true; // This should not be hit, but it is!
    }
  }

  delete [] results;

Thanks, Dave

Upvotes: 2

Views: 8825

Answers (1)

Andreas Brinck
Andreas Brinck

Reputation: 52559

FILE* file = fopen (fileName, "wb");
FILE* file = fopen (fileName, "rb");

Upvotes: 4

Related Questions