1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
#include <iostream>
#include <type_traits>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <fstream>
template < typename T > struct as_bits // a wrapper that reads and writes object of type T as bits
{
static_assert( std::is_trivially_copyable<T>::value ) ;
T value{} ;
as_bits( const T& v = T{} ) : value(v) {}
operator T& () noexcept { return value ; }
operator const T& () const noexcept { return value ; }
friend std::ostream& operator<< ( std::ostream& stm, const as_bits<T>& v )
{ return stm.write( reinterpret_cast< const char* >( std::addressof(v.value) ), sizeof(T) ) ; }
friend std::istream& operator>> ( std::istream& stm, as_bits<T>& v )
{ return stm.read( reinterpret_cast<char*>( std::addressof(v.value) ), sizeof(T) ) ; }
};
int main()
{
const std::string file_name = "test_file.dat" ;
const std::vector< unsigned int > vec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// write contents (as bits) into a file
{
std::ofstream file { file_name, std::ios::binary } ;
file << as_bits<std::size_t>( vec.size() ) ; // write the size of the vector
// write out the integer values
std::copy_n( vec.begin(), vec.size(), std::ostream_iterator< as_bits<unsigned int> >(file) ) ;
}
// read it back into another vector
{
std::vector< unsigned int > vec2 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::ifstream file { file_name, std::ios::binary } ;
// read the size of the vector
as_bits<std::size_t> sz ;
file >> sz ;
vec2.resize(sz) ; // provide enough space for sz values
// read the sz integer values into the vector
using istream_iterator = std::istream_iterator< as_bits<unsigned int> > ;
std::copy_n( istream_iterator(file), vec2.size(), vec2.begin() ) ;
// check if what was read is the data that was written out earlier
if( vec2 == vec ) std::cout << "vec2 == vec: ok. this is what is expected\n" ;
else std::cerr << "something is wrong\n" ;
}
}
|