Want more features on Pastebin? Sign Up, it's FREE!
Guest

Reading values from binary file

By: FizzyGalacticus on Dec 19th, 2012  |  syntax: C++  |  size: 1.18 KB  |  views: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <iostream>
  2. using std::cout;
  3. using std::cin;
  4. using std::endl;
  5. #include <fstream>
  6. using std::ifstream;
  7. using std::ofstream;
  8. using std::ios;
  9. #include <string>
  10. using std::string;
  11. #include <istream>
  12. using std::istream;
  13. #include <sys/stat.h>
  14.  
  15. const unsigned int checkFileSize(const char * &);
  16. const unsigned int readFile(istream &, const int);
  17.  
  18. int main(int argc, const char * argv[])
  19. {
  20.         if(argc > 1)
  21.         {
  22.                 cout << "Filename: " << argv[1] << endl;
  23.                 cout << "File size: " << checkFileSize(argv[1]) << endl;
  24.                 ifstream in;
  25.                
  26.                 in.open(argv[1], ios::in|ios::binary);
  27.                 if(in)
  28.                 {
  29.                         cout << "PID: " << readFile(in,3) << endl;
  30.                         in.close();
  31.                 }
  32.                 else cout << "Couldn't open file!" << endl;
  33.         }
  34.         else cout << "No file given!" << endl;
  35.         return 0;
  36. }
  37.  
  38. const unsigned int checkFileSize(const char * & filename)
  39. {
  40.         struct stat filestatus;
  41.         stat( filename, &filestatus );
  42.         return filestatus.st_size;
  43. }
  44.  
  45. const unsigned int readFile(istream & in, const int numBytes)
  46. {
  47.         char foo[numBytes];
  48.         unsigned int bar = 0;
  49.        
  50.         in.read(foo,sizeof(foo));
  51.        
  52.         for(int i = 0; i < numBytes; i++)
  53.         {
  54.                 bar += (int)foo[i];
  55.                 if(i != (numBytes-1)) bar << 8;
  56.         }
  57.        
  58.         return bar;
  59. }
clone this paste RAW Paste Data