Write to ofstream followed by read with ifstream doesn't read entire file

516 views Asked by At

The following program writes 100 bytes, but doesn't read them all back. Why?

#include <iostream>
#include <random>
#include <vector>
#include <climits>
#include <algorithm>
#include <map>
#include <fstream>
#include <iomanip>

int main()
{
    constexpr size_t file_size{100};
    std::random_device r{};
    auto min = std::numeric_limits<unsigned char>::min();
    auto max = std::numeric_limits<unsigned char>::max();
    std::uniform_int_distribution<size_t> ud{min,max};

    {
        std::ofstream ofs{"otp.bin",std::ios::binary};
        for(size_t i{}; i < file_size; ++i) {
            ofs << static_cast<unsigned char>(ud(r));
        }
        ofs.close(); // not needed? 
    }

    std::ifstream ifs{"otp.bin",std::ios::binary};

    unsigned char c{};
    size_t i{};
    while(ifs >> c) {
        std::cout << std::setw(4) << std::hex << static_cast<unsigned int>(c) << std::dec << ((++i % 10 == 0) ? '\n' : ' ');
    }

    std::cout << '\n' << i << " bytes read.\n";
    return 0;
}

I sometimes get 99, 94, 96, but never 100. I get this behavior on VS2015, clang and gcc.

Here is an online example.

1

There are 1 answers

1
Baum mit Augen On BEST ANSWER
ifs >> c

skips whitespace per default. Put

ifs >> std::noskipws;

before the loop to also read whitespace bytes.


Also

ofs.close(); // not needed? 

Not needed indeed, the file is closed when the stream goes out of scope.