avr39ripe

cppBinTextFileIOCompare

Jun 23rd, 2021
969
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. int main()
  5. {
  6.     std::fstream fileBin;
  7.     std::fstream fileText;
  8.     fileText.open("textFile.txt", std::ios::out | std::ios::in);
  9.     fileBin.open("binaryFile.dat", std::ios::out | std::ios::in |  std::ios::binary);
  10.  
  11.     if (!fileText or !fileBin) { std::cout << "IOERR OUT!\n"; }
  12.  
  13.     int val{ 255 };
  14.     for (int i{ 1 }; i < 10; ++i)
  15.     {
  16.         fileText << val << '\n';
  17.         fileBin.write((char*)(&val), sizeof(int));
  18.         ++val;
  19.     }
  20.  
  21.     fileText.seekg(0, std::ios::beg);
  22.     fileBin.seekg(0, std::ios::beg);
  23.  
  24.     while(!fileBin.eof() or !fileText.eof())
  25.     {
  26.         fileBin.read((char*)(&val), sizeof(int));
  27.  
  28.         if (fileBin.fail()) { break; }
  29.  
  30.  
  31.         std::cout << "Binary: " << val;
  32.  
  33.         fileText >> val;
  34.  
  35.         if (fileText.fail()) { break; }
  36.  
  37.         std::cout << " Text: " << val << '\n';
  38.     }
  39.  
  40.     fileText.close();
  41.     fileBin.close();
  42. };
  43.  
RAW Paste Data