Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- class BinaryIO {
- private:
- FILE * mFile;
- void InternalRead( string & str ) {
- char symbol = 0;
- do {
- fread( reinterpret_cast<void*>( &symbol ), sizeof( symbol ), 1, mFile );
- if( symbol ) {
- str.push_back( symbol );
- }
- } while( symbol != 0 );
- }
- void InternalRead( int & integer ) {
- fread( reinterpret_cast<void*>( &integer ), sizeof( integer ), 1, mFile );
- }
- void InternalRead( float & real ) {
- fread( reinterpret_cast<void*>( &real ), sizeof( real ), 1, mFile );
- }
- void InternalRead( char & byte ) {
- fread( reinterpret_cast<void*>( &byte ), sizeof( byte ), 1, mFile );
- }
- void InternalRead( short & word ) {
- fread( reinterpret_cast<void*>( &word ), sizeof( word ), 1, mFile );
- }
- public:
- enum class Mode {
- Write, Read
- };
- explicit BinaryIO( const string & fileName, const Mode & mode ) {
- Open( fileName, mode );
- }
- ~BinaryIO() {
- Close();
- }
- void Close() {
- fclose( mFile );
- }
- void Open( const string & fileName, const Mode & mode ) {
- if( fopen_s( &mFile, fileName.c_str(), mode == Mode::Write ? "wb" : "rb" )) {
- throw runtime_error( string( "Unable to open file " ) + fileName );
- }
- }
- void Write( const string & str ) const {
- static char zero = 0;
- fwrite( str.c_str(), sizeof( char ), str.size(), mFile );
- fwrite( reinterpret_cast<void*>( &zero ), sizeof( char ), 1, mFile );
- }
- void Write( int integer ) const {
- fwrite( reinterpret_cast<void*>( &integer ), sizeof( integer ), 1, mFile );
- }
- void Write( float real ) const {
- fwrite( reinterpret_cast<void*>( &real ), sizeof( real ), 1, mFile );
- }
- void Write( char byte ) const {
- fwrite( reinterpret_cast<void*>( &byte ), sizeof( byte ), 1, mFile );
- }
- void Write( short word ) const {
- fwrite( reinterpret_cast<void*>( &word ), sizeof( word ), 1, mFile );
- }
- template< class T > T Read( ) {
- T out;
- InternalRead( out );
- return out;
- }
- };
- void main() {
- BinaryIO io( "file.bin", BinaryIO::Mode::Write );
- // write
- io.Write( "This is string" );
- io.Write( 12345 );
- io.Write( 98765.0f );
- io.Write( (char)127 );
- io.Write( (short)16535 );
- io.Close();
- // read
- io.Open( "file.bin", BinaryIO::Mode::Read );
- string str = io.Read<string>();
- int integer = io.Read<int>();
- float real = io.Read<float>();
- char byte = io.Read<char>();
- short word = io.Read<short>();
- io.Close();
- system( "pause" );
- }
Advertisement
Add Comment
Please, Sign In to add comment