C ++ ofstream write在Windows下不起作用。在Linux下正常工作

时间:2014-01-18 14:53:45

标签: c++ linux windows binary ofstream

以下代码在Windows和GNU C ++,VS10,VS12,Intel C ++ 14.0下无效。下面的代码可以在Linux和GNU C ++ 4.7,4.8,Intel C ++ 14,Open64 5.0下工作。在内部测试for循环中使用DIMEN-256替换DIMEN ...工作!?任何的想法?

//============================//
// Read and Write binary file //
// using buffers              //
//============================//

#include <iostream>
#include <fstream>
#include <string>
#include <cmath>

using namespace std;

int main()
{
  // 1. variables and parameters

  const long int DIMEN = static_cast<long int>(pow(10.0,8.0));
  const long int I_DO_MAX = 100;
  const string fileName = "my_file.bin";
  ofstream fileOUT;
  ifstream fileIN;
  double* myArrayAlpha = new double [DIMEN];
  double* myArrayBeta = new double [DIMEN];
  long int i;
  long int j;

  // 2. build the array with some data

  cout << " 1 --> Build the array with some data" << endl;

  for (i = 0; i < DIMEN; i++)
  { myArrayAlpha[i] = static_cast<double>(i); }

  for (i = 0; i < I_DO_MAX; i++)
  {
    // 3. open the file stream

    cout << "-------------->>> " << i << endl;
    cout << " 2 --> Open the file stream" << endl;

    fileOUT.open(fileName.c_str(), ios::out | ios::binary | ios::trunc);
    fileIN.open(fileName.c_str(), ios::in | ios::binary); 

    // 4. test if the file stream is opened 

    cout << " 3 --> Test if the file stream is opened with success" << endl;

    if (!fileOUT.is_open())
    { cout << "Error! The output file stream is not opened. Exit." 
           << endl; return -1; }

    if (!fileIN.is_open())
    { cout << "Error! The input file stream is not opened. Exit." 
           << endl; return -1; }

    // 5. write the contents of myArrayAlpha[] to a file

    cout << " 4 --> Write and then Read to the file" << endl;

    fileIN.seekg(0, fileIN.beg);
    fileOUT.seekp(0);

    fileOUT.write(reinterpret_cast<char*>(&myArrayAlpha[0]), 
                  DIMEN * sizeof(double));
    fileIN.read(reinterpret_cast<char*>(&myArrayBeta[0]), 
                DIMEN * sizeof(double));

    // 6. test that I am writting and reading correctly

    for (j = 0; j < DIMEN; j++) // replace DIMEN 
    {                           // with DIMEN-256 to work under Windows
      if (myArrayAlpha[j] != myArrayBeta[j])
      { cout << myArrayAlpha[j] << endl;
        cout << myArrayBeta[j] << endl;
        cout << "j = " << j << endl;
        cout << "Error!"; return -1; }
    }

    cout << " 5 --> Read and Write with success" << endl;
    cout << " 6 --> Close the I/O streams" << endl;

    // 7. close the file stream

    fileIN.close();
    fileOUT.close();
  }

  // 8. free up the RAM

  delete [] myArrayAlpha;
  delete [] myArrayBeta;

  return 0;
}

1 个答案:

答案 0 :(得分:2)

问题是在write调用之后,您的数据没有被刷新到外部序列,因此它仍然位于内部缓冲区中。在write()之后添加此行:

fileOUT << std::flush;