Das folgende Programm schreibt 100 Bytes, aber liest sie nicht alle zurück. Warum?Schreiben in ofstream gefolgt von Lesen mit ifstream liest nicht die gesamte Datei
#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;
}
ich manchmal 99, 94, 96, aber 100. nie bekomme ich dieses Verhalten auf VS2015, Klirren und gcc.
Here ist ein Online-Beispiel.
Ich bin mir nicht sicher, aber vielleicht müssen Sie den Ausgabestrom nach jedem Schreiben leeren – baliman
Wenn Sie eine Binärdatei schreiben, verwenden Sie unformatierte Eingabe-/Ausgabefunktionen, nicht formatierte Eingabe-/Ausgabefunktionen. (So 'lesen' und' schreiben' nicht Extraktion und Insertion Operatoren.) –