'Using cstdio to read a file written by fstream results in wrong answers

I write a simple array to a file by using fstream. And I get wrong numbers if I use cstdio to read the file. The following is my code.

#include <cstdio>

#include <iostream>
#include <fstream>

int main()
{
  const int array_old[11] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13 };
  
  for ( int i = 0 ; i < 11 ; ++i )
  {
    std::cout << array_old[i] << std::endl;
  }
  
  //******************************************************************************************
  //FILE* pFileOut = fopen( "test.bin", "wb" );
  //
  //fwrite( array_old, sizeof(int), 11, pFileOut );
  //
  //fclose( pFileOut );
  //******************************************************************************************
  
  //******************************************************************************************
  std::fstream ofs( "test.bin", std::ios_base::out | std::ios_base::trunc);
  
  ofs.write( reinterpret_cast<const char*>(array_old), 11 * sizeof(int) );
  
  ofs.close();
  //******************************************************************************************
  
  int array_new[11] = { 0 };
  
  std::cout << std::endl;
  
  for ( int i = 0 ; i < 11 ; ++i )
  {
    std::cout << array_new[i] << std::endl;
  }
  
  //******************************************************************************************
  FILE* pFileIn = fopen( "test.bin", "rb" );
  
  fread( array_new, sizeof(int), 11, pFileIn );
  
  fclose( pFileIn );
  //******************************************************************************************
  
  //******************************************************************************************
  //std::fstream ifs( "test.bin", std::ios_base::in  );
  //
  //ifs.read( reinterpret_cast<char*>(array_new), 11 * sizeof(int) );
  //
  //ifs.close();
  //******************************************************************************************
  
  std::cout << std::endl;
  
  for ( int i = 0 ; i < 11 ; ++i )
  {
    std::cout << array_new[i] << std::endl;
  }
  
  return 0;
}

The result is

1
2
3
4
5
6
7
8
9
10
13

0
0
0
0
0
0
0
0
0
0
0

1
2
3
4
5
6
7
8
9
2573
3328

The last two numbers are wrong. It's noted that only the combination of using (output,input) = (fstream, cstdio) results in wrong numbers. The other three combinations are fine.

The compiler I use is g++ (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0.

Thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source