Search code examples
c++binaryfilesifstreamofstreamformatted

Can I do an Unformatted Write to a File Then a Formatted Read From a File for Integral Types?


Given that I write an vector of integers to temporary file unformatted:

ofstream foo("foo.txt", ios::binary);
const auto length= size(output);

foo.write(reinterpret_cast<const char*>(length), sizeof(length));

if(!empty(input)) foo.write(reinterpret_cast<const char*>(data(output)), sizeof(decltype(output)::value_type) * length);

Can I do the following formatted read later from the file where input is the same type as output:

ifstream foo("foo.txt", ios::binary);
size_t size;

foo.read(reinterpret_cast<char*>(size), sizeof(size));
input.resize(size);

if(!empty(input)) copy(istream_iterator<decltype(output)::value_type>(foo), istream_iterator<decltype(output)::value_type>(), begin(input));

Solution

  • Can I do an Unformatted Write to a File Then a Formatted Read From a File for Integral Types?

    No, you can't do that.

    The contents of a file to which data are written using unformatted write will be very different from formatted write. An formatted read cannot accurately interpret the unformatted data.