将浮点数组保存到二进制文件和回读的问题(C ++)

时间:2011-01-13 13:17:58

标签: c++ arrays floating-point fwrite fread

我试图简单地将一个浮点值数组写入文件然后再读回来 我曾尝试直接从数组中编写它,但是当读回它时,我一直为长度大于153的数组遇到问题。代码示例为了清晰起见逐个写入每个浮点值。

对于索引大于或等于153的值,它们的值为153.0,它们应为153.0,154.0,155.0,......

为什么这段代码对我不起作用?

  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;

谢谢, 戴夫

1 个答案:

答案 0 :(得分:3)

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