reader.cpp

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc2100/fall2026/notes/char/code/reader.cpp
 
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char * argv[]) {

     string fileName {"data.raw"};
     if (argc > 1) {
         fileName = argv[1];
     }

     ifstream inFile(fileName, ios::binary);

     cout << "Reading character by character" << endl; 
     char letter;

     while(inFile) {
        inFile.read(reinterpret_cast<char *>(&letter),sizeof(letter));
        cout << letter << " ";
     }
     cout << endl;

     inFile.clear();
     inFile.seekg(0, ios::beg);

     cout << "Reading character by character as int" << endl; 

     while(inFile) {
        inFile.read(reinterpret_cast<char *>(&letter),sizeof(letter));
        cout << static_cast<int>(letter) << " ";
     }
     cout << endl;

     inFile.clear();
     inFile.seekg(0, ios::beg);

     cout << "Reading short by short" << endl; 
     short shortVal;
     cout << hex;

     while(inFile) {
        inFile.read(reinterpret_cast<char *>(&shortVal),sizeof(shortVal));
        cout << shortVal << " ";
     }
     cout << endl;

     inFile.clear();
     inFile.seekg(0, ios::beg);

     cout << endl << endl;

     cout << "byte by byte as short MSB - LSB" << endl;
     char byte;
     short last; 
     while(inFile) {
        inFile.read(reinterpret_cast<char *>(&byte),sizeof(byte));
        last = static_cast<int>(byte) << 8;
        inFile.read(reinterpret_cast<char *>(&byte),sizeof(byte));
        last += static_cast<int>(byte);
        cout << last << " ";
     }
     cout << endl;

     inFile.clear();
     inFile.seekg(0, ios::beg);

     cout << "byte by byte as short LSB - MSB" << endl;
     while(inFile) {
        inFile.read(reinterpret_cast<char *>(&byte),sizeof(byte));
        last = static_cast<int>(byte);
        inFile.read(reinterpret_cast<char *>(&byte),sizeof(byte));
        last += (static_cast<int>(byte) << 8);
        cout << last << " ";
     }
     cout << endl;

     inFile.close();

     return 0;
}