Advertisement
avr39ripe

cppFileReaderClassInheritanceDemo

Sep 28th, 2021
844
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <fstream>
  4.  
  5.  
  6. class FileReader
  7. {
  8. protected:
  9.     std::string path;
  10.     std::ifstream inf;
  11. public:
  12.     FileReader(std::string pathP) : path{ pathP }, inf{pathP}
  13.     {
  14.         if (!inf) { throw std::runtime_error("I/O Error!"); }
  15.     }
  16.  
  17.     virtual void display(const char byte)const
  18.     {
  19.         std::cout << byte;
  20.     }
  21.  
  22.     const FileReader& show()
  23.     {
  24.         while (!inf.eof())
  25.         {
  26.             display(inf.get());
  27.         }
  28.         return *this;
  29.     }
  30.     virtual ~FileReader() { inf.close(); }
  31. };
  32.  
  33. class FileReaderASCII : public FileReader
  34. {
  35. public:
  36.     FileReaderASCII(std::string pathP) : FileReader{ pathP } {}
  37.     void display(const char byte) const override
  38.     {
  39.         if (byte > 0)
  40.         {
  41.             std::cout << static_cast<unsigned int>(byte) << ' ';
  42.         }
  43.     }
  44. };
  45.  
  46. class FileReaderBIN : public FileReader
  47. {
  48. public:
  49.     FileReaderBIN(std::string pathP) : FileReader{ pathP } {}
  50.     void display(const char byte) const override
  51.     {
  52.         if (byte > 0)
  53.         {
  54.             for (int bit{ 7 }, mask{1}; bit >= 0; --bit, mask  = (1 << bit))
  55.             {
  56.                 std::cout << static_cast<bool>(byte & mask);
  57.             }
  58.             std::cout << ' ';
  59.         }
  60.     }
  61. };
  62.  
  63. int main()
  64. {
  65.     std::unique_ptr<FileReader> readers[3];
  66.     // CHANGE THIS TO REAL FILENAME PATH!!!
  67.     std::string fileName{ "../ConsoleApplication8/ConsoleApplication8.cpp" };
  68.     try
  69.     {
  70.         readers[0] = std::make_unique<FileReader>(fileName);
  71.         readers[1] = std::make_unique<FileReaderASCII>(fileName);
  72.         readers[2] = std::make_unique<FileReaderBIN>(fileName);
  73.                
  74.         for (const auto& reader : readers)
  75.         {
  76.             std::cout << "\n####### Output for " << typeid(*reader).name() << "#######\n";
  77.             reader->show();
  78.         }
  79.     }
  80.     catch(std::exception& ex)
  81.     {
  82.         std::cout << "ERROR: " << ex.what() << '\n';
  83.         return -1;
  84.     }
  85. }
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement