简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM