2

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

6
  • 2
    There is no C++ to be seen here. This is all C. Please do not confuse those. If you post this as a C++ question, you will get comments about how you should use vector and iostream. Commented Jan 13, 2011 at 13:22
  • 1
    You must specify that you're writing to and reading from a binary file. Check this link: cplusplus.com/reference/clibrary/cstdio/fopen If your don't do so, fread will stop reading when it hits an EOF characters, which is quite possible, since you're writing some random floats. Commented Jan 13, 2011 at 13:22
  • @Space_COwbOy what about the delete [] results; line at the end? :-) Commented Jan 13, 2011 at 13:22
  • He's newing memory so it's obviously compiled with a C++ compiler Commented Jan 13, 2011 at 13:23
  • @Pointy: Dang, I overread that. Commented Jan 13, 2011 at 13:24

1 Answer 1

4
FILE* file = fopen (fileName, "wb");
FILE* file = fopen (fileName, "rb");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.