c++windows-10stdvectorostreamvisual-c++-2017

ofstream::write writes zeros for part of the file


I would like to write the contents of a vector< int> to a binary file. This current program is supposed to save the integers 0 to 99 in the file, but it only saves the first 26 integers.

std::vector<int> vector;
for (int i = 0; i < 100; i++) vector.push_back(i);

std::ofstream outfile("file.bin", std::ios::binary);
outfile.write(reinterpret_cast<const char *>(&vector[0]), sizeof(int)*vector.size());
outfile.close();

std::ifstream file("file.bin");
file.seekg(0, std::ios_base::end);
std::size_t size = file.tellg();
file.seekg(0, std::ios_base::beg);
std::vector<int> vectorRead(size / sizeof(int));
file.read((char*)&vectorRead[0], size);
file.close();

for (int i = 0; i < vector.size(); i++) {
    if (vector.at(i) != vectorRead.at(i)) std::cout << vector.at(i) << ", " << vectorRead.at(i) << std::endl;
}

The output of the code is:

26, 0
27, 0
...
99, 0

How can I write the whole vector to a file?


Solution

  • As user253751 and Marek R pointed out, the issue was I was not reading in binary mode.

    Before:

    std::ifstream file("file.bin");
    

    Corrected:

    std::ifstream file("file.bin", std::ios::binary);