Read arithmetic binary data using fstreams #2

unsigned short fread_unsigned_short(ifstream &input_file) { //note that the ifstream is passed by reference
    unsigned short num;
    //the cast reinterpretation is very importnant
    input_file.read(reinterpret_cast < char * > (&num),sizeof(unsigned short));
    return num;
}

ifstream input_data;
input_data.open("input.dat",ios::in | ios::binary); //note the modifiers that denote both input file and binary mode
unsigned short num=fread_unsigned_short(input_data);

/*
The above function can be generalized to any numeric datatype like integers, floats e.t.c.
just replace the type 'unsigned short' with the wanted type
*/

source

Comments are closed.